precedents.py démarre le conteneur Ollama s'il ne répond pas, puis relance ; testé
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ac86d8f6cc
commit
4d926ecddc
1 file changed
+52
-7
+52
-7
@@ -10,8 +10,8 @@ stations, avec leur provenance (relue, non relue) : à lui de juger si elles val
|
|||||||
python3 labeling/precedents.py --check # contrôle de la logique, sans Ollama
|
python3 labeling/precedents.py --check # contrôle de la logique, sans Ollama
|
||||||
|
|
||||||
L'index (.index/, hors de git) garde le vecteur de chaque texte : à chaque appel, seules les étiquettes nouvelles ou
|
L'index (.index/, hors de git) garde le vecteur de chaque texte : à chaque appel, seules les étiquettes nouvelles ou
|
||||||
modifiées passent par le modèle. Modèle : bge-m3 servi par Ollama, le conteneur ollama-bge-m3 (`docker start
|
modifiées passent par le modèle. Modèle : bge-m3 servi par Ollama, le conteneur ollama-bge-m3, que l'outil démarre
|
||||||
ollama-bge-m3`) ; OLLAMA_URL et RAG_MODELE pour en changer. Bibliothèque standard seulement.
|
lui-même s'il ne répond pas (`docker start`) ; OLLAMA_URL et RAG_MODELE pour en changer. Bibliothèque standard seulement.
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
import glob
|
import glob
|
||||||
@@ -19,7 +19,9 @@ import hashlib
|
|||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import os
|
import os
|
||||||
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import time
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -27,6 +29,7 @@ from pathlib import Path
|
|||||||
ICI = Path(__file__).resolve().parent
|
ICI = Path(__file__).resolve().parent
|
||||||
URL = os.environ.get("OLLAMA_URL", "http://10.0.2.140:11435") # le port publié par le conteneur ollama-bge-m3
|
URL = os.environ.get("OLLAMA_URL", "http://10.0.2.140:11435") # le port publié par le conteneur ollama-bge-m3
|
||||||
MODELE = os.environ.get("RAG_MODELE", "bge-m3:567m")
|
MODELE = os.environ.get("RAG_MODELE", "bge-m3:567m")
|
||||||
|
CONTENEUR = "ollama-bge-m3" # démarré par l'outil s'il ne répond pas
|
||||||
INDEX = ICI / ".index" / f"{MODELE.replace(':', '_')}.json"
|
INDEX = ICI / ".index" / f"{MODELE.replace(':', '_')}.json"
|
||||||
LOT = 32 # textes par appel au modèle
|
LOT = 32 # textes par appel au modèle
|
||||||
|
|
||||||
@@ -70,14 +73,30 @@ def norme(v):
|
|||||||
return [round(x / n, 5) for x in v]
|
return [round(x / n, 5) for x in v]
|
||||||
|
|
||||||
|
|
||||||
|
def demarrer_ollama(attente=120):
|
||||||
|
"""Le conteneur ollama-bge-m3 arrêté : `docker start`, puis attendre qu'il réponde -> True s'il répond."""
|
||||||
|
if subprocess.run(["docker", "start", CONTENEUR], capture_output=True).returncode:
|
||||||
|
return False
|
||||||
|
fin = time.monotonic() + attente
|
||||||
|
while time.monotonic() < fin:
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"{URL}/api/version", timeout=5):
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
time.sleep(2)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def vectoriser(textes):
|
def vectoriser(textes):
|
||||||
corps = json.dumps({"model": MODELE, "input": textes}).encode()
|
corps = json.dumps({"model": MODELE, "input": textes}).encode()
|
||||||
req = urllib.request.Request(f"{URL}/api/embed", corps, {"Content-Type": "application/json"})
|
req = urllib.request.Request(f"{URL}/api/embed", corps, {"Content-Type": "application/json"})
|
||||||
try:
|
for essai in (1, 2): # Ollama arrêté : on démarre son conteneur, une fois, puis on relance
|
||||||
with urllib.request.urlopen(req, timeout=300) as r:
|
try:
|
||||||
return [norme(v) for v in json.load(r)["embeddings"]]
|
with urllib.request.urlopen(req, timeout=300) as r:
|
||||||
except OSError as err:
|
return [norme(v) for v in json.load(r)["embeddings"]]
|
||||||
sys.exit(f"Ollama injoignable sur {URL} ({err}) : `docker start ollama-bge-m3`, ou OLLAMA_URL.")
|
except OSError as err:
|
||||||
|
if essai == 2 or not demarrer_ollama():
|
||||||
|
sys.exit(f"Ollama injoignable sur {URL} ({err}) : `docker start {CONTENEUR}`, ou OLLAMA_URL.")
|
||||||
|
|
||||||
|
|
||||||
def index_a_jour(toutes):
|
def index_a_jour(toutes):
|
||||||
@@ -121,6 +140,32 @@ def check():
|
|||||||
assert [x["categorie"] for _, x in chercher("", [a, b], vec, [0.0, 1.0])] == ["B", "A"]
|
assert [x["categorie"] for _, x in chercher("", [a, b], vec, [0.0, 1.0])] == ["B", "A"]
|
||||||
assert [x["categorie"] for _, x in chercher("", [a, b], vec, [0.0, 1.0], exclure=("T", e["debut"], e["fin"]))] == ["A"]
|
assert [x["categorie"] for _, x in chercher("", [a, b], vec, [0.0, 1.0], exclure=("T", e["debut"], e["fin"]))] == ["A"]
|
||||||
assert [x["categorie"] for _, x in chercher("", [a, b], vec, [0.0, 1.0], famille="A")] == ["A"]
|
assert [x["categorie"] for _, x in chercher("", [a, b], vec, [0.0, 1.0], famille="A")] == ["A"]
|
||||||
|
appels, reponses = [], iter([OSError("refusé"), {"embeddings": [[3.0, 4.0]]}]) # Ollama arrêté : démarré, puis la relance passe
|
||||||
|
|
||||||
|
class Reponse:
|
||||||
|
def __init__(self, r):
|
||||||
|
self.r = r
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return json.dumps(self.r).encode()
|
||||||
|
|
||||||
|
def ouvrir(*a, **k):
|
||||||
|
r = next(reponses)
|
||||||
|
if isinstance(r, Exception):
|
||||||
|
raise r
|
||||||
|
return Reponse(r)
|
||||||
|
avant = urllib.request.urlopen, globals()["demarrer_ollama"]
|
||||||
|
urllib.request.urlopen, globals()["demarrer_ollama"] = ouvrir, lambda: appels.append(1) or True
|
||||||
|
try:
|
||||||
|
assert vectoriser(["x"]) == [[0.6, 0.8]] and appels == [1], appels
|
||||||
|
finally:
|
||||||
|
urllib.request.urlopen, globals()["demarrer_ollama"] = avant
|
||||||
print("ok")
|
print("ok")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user