Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -4,7 +4,7 @@ from typing import Optional
|
|
4 |
|
5 |
# ✅ Modules de LlamaIndex
|
6 |
from llama_index.core.settings import Settings
|
7 |
-
from llama_index.core import Document
|
8 |
from llama_index.llms.llama_cpp import LlamaCPP
|
9 |
from llama_index.core.node_parser import SemanticSplitterNodeParser
|
10 |
|
@@ -31,7 +31,6 @@ MODEL_NAME = "BAAI/bge-small-en-v1.5"
|
|
31 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, cache_dir=CACHE_DIR)
|
32 |
model = AutoModel.from_pretrained(MODEL_NAME, cache_dir=CACHE_DIR)
|
33 |
|
34 |
-
|
35 |
def get_embedding(text: str):
|
36 |
with torch.no_grad():
|
37 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
@@ -54,10 +53,8 @@ async def chunk_text(data: ChunkRequest):
|
|
54 |
print(f"✅ Texte reçu ({len(data.text)} caractères) : {data.text[:200]}...")
|
55 |
print("✅ ✔️ Reçu – On passe à la configuration du modèle LLM...")
|
56 |
|
57 |
-
|
58 |
-
# ✅ Chargement du modèle LLM depuis Hugging Face en ligne (pas de .gguf local)
|
59 |
llm = LlamaCPP(
|
60 |
-
|
61 |
model_url="https://huggingface.co/leafspark/Mistral-7B-Instruct-v0.2-Q4_K_M-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
|
62 |
temperature=0.1,
|
63 |
max_new_tokens=512,
|
@@ -65,31 +62,30 @@ async def chunk_text(data: ChunkRequest):
|
|
65 |
generate_kwargs={"top_p": 0.95},
|
66 |
model_kwargs={"n_gpu_layers": 1},
|
67 |
)
|
68 |
-
|
69 |
print("✅ ✔️ Modèle LLM chargé sans erreur on continue...")
|
70 |
|
71 |
-
# ✅
|
72 |
class SimpleEmbedding:
|
73 |
def get_text_embedding(self, text: str):
|
74 |
return get_embedding(text)
|
75 |
|
76 |
try:
|
77 |
-
Settings.llm
|
78 |
-
Settings.
|
79 |
-
|
|
|
|
|
|
|
80 |
except Exception as e:
|
81 |
print(f"❌ Erreur dans la configuration des Settings : {e}")
|
82 |
return {"error": str(e)}
|
83 |
|
84 |
-
|
85 |
-
import sys
|
86 |
-
|
87 |
print("✅ LLM et embedding configurés - prêt pour le split")
|
88 |
-
|
89 |
print("✅ Début du split sémantique...", flush=True)
|
90 |
|
91 |
-
#
|
92 |
-
parser = SemanticSplitterNodeParser.from_defaults(llm=
|
93 |
fallback_splitter = Settings.node_parser # fallback = splitter par défaut
|
94 |
|
95 |
doc = Document(text=data.text)
|
@@ -98,28 +94,18 @@ async def chunk_text(data: ChunkRequest):
|
|
98 |
nodes = parser.get_nodes_from_documents([doc])
|
99 |
print(f"✅ Nombre de chunks générés : {len(nodes)}")
|
100 |
print(f"🧩 Exemple chunk : {nodes[0].text[:100]}...")
|
101 |
-
|
102 |
except Exception as e:
|
103 |
import traceback
|
104 |
traceback.print_exc()
|
105 |
print(f"❌ Erreur lors du split sémantique : {e}")
|
106 |
-
return {"error": str(e)}
|
107 |
-
|
108 |
-
|
109 |
|
|
|
110 |
nodes = fallback_splitter.get_nodes_from_documents([doc])
|
111 |
print(f"⚠️ Split fallback utilisé - chunks générés : {len(nodes)}")
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
# ✅ Découpage sémantique intelligent
|
117 |
-
# parser = SemanticSplitterNodeParser.from_defaults()
|
118 |
-
# nodes = parser.get_nodes_from_documents([Document(text=data.text)])
|
119 |
-
|
120 |
-
# ✅ Vérification du nombre de chunks générés
|
121 |
-
print(f"✅ Nombre de chunks générés : {len(nodes)}")
|
122 |
-
|
123 |
return {
|
124 |
"chunks": [node.text for node in nodes],
|
125 |
"metadatas": [node.metadata for node in nodes],
|
@@ -130,7 +116,6 @@ async def chunk_text(data: ChunkRequest):
|
|
130 |
"error": None # ← essentiel pour que n8n voie "rien à signaler"
|
131 |
}
|
132 |
|
133 |
-
|
134 |
except Exception as e:
|
135 |
return {"error": str(e)}
|
136 |
|
|
|
4 |
|
5 |
# ✅ Modules de LlamaIndex
|
6 |
from llama_index.core.settings import Settings
|
7 |
+
from llama_index.core import Document, ServiceContext
|
8 |
from llama_index.llms.llama_cpp import LlamaCPP
|
9 |
from llama_index.core.node_parser import SemanticSplitterNodeParser
|
10 |
|
|
|
31 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, cache_dir=CACHE_DIR)
|
32 |
model = AutoModel.from_pretrained(MODEL_NAME, cache_dir=CACHE_DIR)
|
33 |
|
|
|
34 |
def get_embedding(text: str):
|
35 |
with torch.no_grad():
|
36 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
|
|
53 |
print(f"✅ Texte reçu ({len(data.text)} caractères) : {data.text[:200]}...")
|
54 |
print("✅ ✔️ Reçu – On passe à la configuration du modèle LLM...")
|
55 |
|
56 |
+
# ✅ Chargement du modèle LLM depuis Hugging Face (GGUF distant)
|
|
|
57 |
llm = LlamaCPP(
|
|
|
58 |
model_url="https://huggingface.co/leafspark/Mistral-7B-Instruct-v0.2-Q4_K_M-GGUF/resolve/main/mistral-7b-instruct-v0.2.Q4_K_M.gguf",
|
59 |
temperature=0.1,
|
60 |
max_new_tokens=512,
|
|
|
62 |
generate_kwargs={"top_p": 0.95},
|
63 |
model_kwargs={"n_gpu_layers": 1},
|
64 |
)
|
65 |
+
|
66 |
print("✅ ✔️ Modèle LLM chargé sans erreur on continue...")
|
67 |
|
68 |
+
# ✅ Définition d’un wrapper simple pour l’embedding local
|
69 |
class SimpleEmbedding:
|
70 |
def get_text_embedding(self, text: str):
|
71 |
return get_embedding(text)
|
72 |
|
73 |
try:
|
74 |
+
# 🛠️ Remplace Settings.llm + embed_model par ServiceContext
|
75 |
+
Settings.service_context = ServiceContext.from_defaults(
|
76 |
+
llm=llm,
|
77 |
+
embed_model=SimpleEmbedding()
|
78 |
+
)
|
79 |
+
print("✅ ✔️ Settings configurés via ServiceContext (LLM + Embedding)")
|
80 |
except Exception as e:
|
81 |
print(f"❌ Erreur dans la configuration des Settings : {e}")
|
82 |
return {"error": str(e)}
|
83 |
|
|
|
|
|
|
|
84 |
print("✅ LLM et embedding configurés - prêt pour le split")
|
|
|
85 |
print("✅ Début du split sémantique...", flush=True)
|
86 |
|
87 |
+
# ✅ Utilisation du Semantic Splitter avec le LLM actuel
|
88 |
+
parser = SemanticSplitterNodeParser.from_defaults(llm=llm)
|
89 |
fallback_splitter = Settings.node_parser # fallback = splitter par défaut
|
90 |
|
91 |
doc = Document(text=data.text)
|
|
|
94 |
nodes = parser.get_nodes_from_documents([doc])
|
95 |
print(f"✅ Nombre de chunks générés : {len(nodes)}")
|
96 |
print(f"🧩 Exemple chunk : {nodes[0].text[:100]}...")
|
97 |
+
|
98 |
except Exception as e:
|
99 |
import traceback
|
100 |
traceback.print_exc()
|
101 |
print(f"❌ Erreur lors du split sémantique : {e}")
|
102 |
+
return {"error": str(e)}
|
|
|
|
|
103 |
|
104 |
+
# Fallback option (non utilisé ici)
|
105 |
nodes = fallback_splitter.get_nodes_from_documents([doc])
|
106 |
print(f"⚠️ Split fallback utilisé - chunks générés : {len(nodes)}")
|
107 |
|
108 |
+
# ✅ Résultat complet pour l’API
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
return {
|
110 |
"chunks": [node.text for node in nodes],
|
111 |
"metadatas": [node.metadata for node in nodes],
|
|
|
116 |
"error": None # ← essentiel pour que n8n voie "rien à signaler"
|
117 |
}
|
118 |
|
|
|
119 |
except Exception as e:
|
120 |
return {"error": str(e)}
|
121 |
|