Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import unicodedata
|
4 |
+
import re
|
5 |
+
import numpy as np
|
6 |
+
from pathlib import Path
|
7 |
+
from transformers import AutoTokenizer, AutoModel
|
8 |
+
from sklearn.feature_extraction.text import HashingVectorizer
|
9 |
+
from sklearn.preprocessing import normalize as sk_normalize
|
10 |
+
import chromadb
|
11 |
+
import joblib
|
12 |
+
import pickle
|
13 |
+
import scipy.sparse
|
14 |
+
import textwrap
|
15 |
+
import os
|
16 |
+
import json # Για το διάβασμα του JSON κατά το setup
|
17 |
+
import tqdm.auto as tq # Για progress bars κατά το setup
|
18 |
+
|
19 |
+
# --------------------------- CONFIG για ChatbotVol107 -----------------------------------
|
20 |
+
# --- Ρυθμίσεις Μοντέλου και Βάσης Δεδομένων ---
|
21 |
+
MODEL_NAME = "nlpaueb/bert-base-greek-uncased-v1"
|
22 |
+
PERSISTENT_STORAGE_ROOT = Path("/data") # Για Hugging Face Spaces Persistent Storage
|
23 |
+
DB_DIR_APP = PERSISTENT_STORAGE_ROOT / "chroma_db_ChatbotVol107"
|
24 |
+
COL_NAME = "collection_chatbotvol107"
|
25 |
+
ASSETS_DIR_APP = PERSISTENT_STORAGE_ROOT / "assets_ChatbotVol107"
|
26 |
+
DATA_PATH_FOR_SETUP = "./dataset14.json"
|
27 |
+
|
28 |
+
# --- Ρυθμίσεις για Google Cloud Storage για τα PDF links ---
|
29 |
+
GCS_BUCKET_NAME = "chatbotthesisihu" # Το δικό σας GCS Bucket Name
|
30 |
+
GCS_PUBLIC_URL_PREFIX = f"https://storage.googleapis.com/{GCS_BUCKET_NAME}/"
|
31 |
+
# -------------------------------------------------------------
|
32 |
+
|
33 |
+
# --- Παράμετροι Αναζήτησης και Μοντέλου ---
|
34 |
+
CHUNK_SIZE = 512
|
35 |
+
CHUNK_OVERLAP = 40
|
36 |
+
BATCH_EMB = 32 # Για τη δημιουργία των embeddings κατά το setup
|
37 |
+
ALPHA_BASE = 0.2 # Βέλτιστη τιμή alpha που βρήκατε
|
38 |
+
ALPHA_LONGQ = 0.35# Βέλτιστη τιμή alpha για μεγάλα queries που βρήκατε
|
39 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
40 |
+
|
41 |
+
print(f"Running ChatbotVol107 on device: {DEVICE}")
|
42 |
+
print(f"Using model: {MODEL_NAME}")
|
43 |
+
|
44 |
+
# === ΛΟΓΙΚΗ ΔΗΜΙΟΥΡΓΙΑΣ ΒΑΣΗΣ ΚΑΙ ASSETS (Αν δεν υπάρχουν) ===
|
45 |
+
def setup_database_and_assets():
|
46 |
+
print("Checking if database and assets need to be created...")
|
47 |
+
# Έλεγχος ύπαρξης βασικών αρχείων για να αποφασιστεί αν το setup χρειάζεται
|
48 |
+
# Ο έλεγχος col.count()
|
49 |
+
run_setup = True
|
50 |
+
if DB_DIR_APP.exists() and ASSETS_DIR_APP.exists() and (ASSETS_DIR_APP / "ids.pkl").exists():
|
51 |
+
try:
|
52 |
+
client_check = chromadb.PersistentClient(path=str(DB_DIR_APP.resolve()))
|
53 |
+
collection_check = client_check.get_collection(name=COL_NAME)
|
54 |
+
if collection_check.count() > 0:
|
55 |
+
print("✓ Database and assets appear to exist and collection is populated. Skipping setup.")
|
56 |
+
run_setup = False
|
57 |
+
else:
|
58 |
+
print("Collection exists but is empty. Proceeding with setup.")
|
59 |
+
if DB_DIR_APP.exists(): # Καθαρισμός αν η βάση υπάρχει αλλά είναι ελλιπής/άδεια
|
60 |
+
import shutil
|
61 |
+
print(f"Attempting to clean up existing empty/corrupt DB directory: {DB_DIR_APP}")
|
62 |
+
shutil.rmtree(DB_DIR_APP)
|
63 |
+
except Exception as e_check: # Π.χ. η συλλογή δεν υπάρχει
|
64 |
+
print(f"Database or collection check failed (Error: {e_check}). Proceeding with setup.")
|
65 |
+
if DB_DIR_APP.exists(): # Καθαρισμός αν η βάση φαίνεται κατεστραμμένη
|
66 |
+
import shutil
|
67 |
+
print(f"Attempting to clean up existing corrupt DB directory: {DB_DIR_APP}")
|
68 |
+
shutil.rmtree(DB_DIR_APP)
|
69 |
+
|
70 |
+
if not run_setup:
|
71 |
+
return True # Το setup δεν χρειάζεται
|
72 |
+
|
73 |
+
print(f"!Database/Assets not found or incomplete. Starting setup process.")
|
74 |
+
print(f"This will take a very long time, especially on the first run !")
|
75 |
+
|
76 |
+
ASSETS_DIR_APP.mkdir(parents=True, exist_ok=True)
|
77 |
+
DB_DIR_APP.mkdir(parents=True, exist_ok=True)
|
78 |
+
|
79 |
+
# --- Helper συναρτήσεις για το setup (τοπικές σε αυτή τη συνάρτηση) ---
|
80 |
+
def _strip_acc_setup(s:str)->str: return ''.join(ch for ch in unicodedata.normalize('NFD', s) if not unicodedata.combining(ch))
|
81 |
+
_STOP_SETUP = {"σχετικο","σχετικά","με","και"}
|
82 |
+
def _preprocess_setup(txt:str)->str:
|
83 |
+
txt = _strip_acc_setup(txt.lower())
|
84 |
+
txt = re.sub(r"[^a-zα-ω0-9 ]", " ", txt)
|
85 |
+
txt = re.sub(r"\s+", " ", txt).strip()
|
86 |
+
return " ".join(w for w in txt.split() if w not in _STOP_SETUP)
|
87 |
+
|
88 |
+
def _chunk_text_setup(text, tokenizer_setup):
|
89 |
+
token_ids = tokenizer_setup.encode(text, add_special_tokens=False)
|
90 |
+
if len(token_ids) <= (CHUNK_SIZE - 2): return [text]
|
91 |
+
ids_with_special_tokens = tokenizer_setup(text, truncation=False, padding=False)["input_ids"]
|
92 |
+
effective_chunk_size = CHUNK_SIZE
|
93 |
+
step = effective_chunk_size - CHUNK_OVERLAP
|
94 |
+
chunks = []
|
95 |
+
for i in range(0, len(ids_with_special_tokens), step):
|
96 |
+
current_chunk_ids = ids_with_special_tokens[i:i+effective_chunk_size]
|
97 |
+
if not current_chunk_ids: break
|
98 |
+
if len(chunks) > 0 and len(current_chunk_ids) < CHUNK_OVERLAP:
|
99 |
+
if len(ids_with_special_tokens) - i < effective_chunk_size: pass
|
100 |
+
else: break
|
101 |
+
decoded_chunk = tokenizer_setup.decode(current_chunk_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True).strip()
|
102 |
+
if decoded_chunk: chunks.append(decoded_chunk)
|
103 |
+
return chunks if chunks else [text]
|
104 |
+
|
105 |
+
def _cls_embed_setup(texts, tokenizer_setup, model_setup, bs=BATCH_EMB):
|
106 |
+
out_embeddings = []
|
107 |
+
for i in tq.tqdm(range(0, len(texts), bs), desc="Embedding texts for DB setup"):
|
108 |
+
enc = tokenizer_setup(texts[i:i+bs], padding=True, truncation=True, max_length=CHUNK_SIZE, return_tensors="pt").to(DEVICE)
|
109 |
+
with torch.no_grad():
|
110 |
+
model_output = model_setup(**enc)
|
111 |
+
last_hidden_state = model_output.last_hidden_state
|
112 |
+
cls_embedding = last_hidden_state[:, 0, :]
|
113 |
+
cls_normalized = torch.nn.functional.normalize(cls_embedding, p=2, dim=1)
|
114 |
+
out_embeddings.append(cls_normalized.cpu())
|
115 |
+
return torch.cat(out_embeddings).numpy()
|
116 |
+
|
117 |
+
# --- Κύρια Λογική του Setup ---
|
118 |
+
print(f"⏳ (Setup) Loading Model ({MODEL_NAME}) and Tokenizer...")
|
119 |
+
tokenizer_setup = AutoTokenizer.from_pretrained(MODEL_NAME)
|
120 |
+
model_setup = AutoModel.from_pretrained(MODEL_NAME).to(DEVICE).eval()
|
121 |
+
print("✓ (Setup) Model and Tokenizer loaded.")
|
122 |
+
|
123 |
+
print(f"⏳ (Setup) Reading & chunking JSON data from {DATA_PATH_FOR_SETUP}...")
|
124 |
+
if not Path(DATA_PATH_FOR_SETUP).exists():
|
125 |
+
print(f"!!! CRITICAL SETUP ERROR: Dataset file {DATA_PATH_FOR_SETUP} not found in the Space repo! Please upload it.")
|
126 |
+
return False
|
127 |
+
|
128 |
+
with open(DATA_PATH_FOR_SETUP, encoding="utf-8") as f: docs_json = json.load(f)
|
129 |
+
|
130 |
+
raw_chunks_setup, pre_chunks_setup, metas_setup, ids_list_setup = [], [], [], []
|
131 |
+
for d_setup in tq.tqdm(docs_json, desc="(Setup) Processing documents"):
|
132 |
+
doc_text = d_setup.get("text")
|
133 |
+
if not doc_text: continue
|
134 |
+
chunked_doc_texts = _chunk_text_setup(doc_text, tokenizer_setup)
|
135 |
+
if not chunked_doc_texts: continue
|
136 |
+
for idx, chunk in enumerate(chunked_doc_texts):
|
137 |
+
if not chunk.strip(): continue
|
138 |
+
raw_chunks_setup.append(chunk)
|
139 |
+
pre_chunks_setup.append(_preprocess_setup(chunk))
|
140 |
+
metas_setup.append({"id": d_setup["id"], "title": d_setup["title"], "url": d_setup["url"], "chunk_num": idx+1, "total_chunks": len(chunked_doc_texts)})
|
141 |
+
ids_list_setup.append(f'{d_setup["id"]}_c{idx+1}')
|
142 |
+
|
143 |
+
print(f" → (Setup) Total chunks created: {len(raw_chunks_setup):,}")
|
144 |
+
if not raw_chunks_setup:
|
145 |
+
print("!!! CRITICAL SETUP ERROR: No chunks were created from the dataset.")
|
146 |
+
return False
|
147 |
+
|
148 |
+
print("⏳ (Setup) Building lexical matrices (TF-IDF)...")
|
149 |
+
char_vec_setup = HashingVectorizer(analyzer="char_wb", ngram_range=(2,5), n_features=2**20, norm=None, alternate_sign=False, binary=True)
|
150 |
+
word_vec_setup = HashingVectorizer(analyzer="word", ngram_range=(1,2), n_features=2**19, norm=None, alternate_sign=False, binary=True)
|
151 |
+
X_char_setup = sk_normalize(char_vec_setup.fit_transform(pre_chunks_setup))
|
152 |
+
X_word_setup = sk_normalize(word_vec_setup.fit_transform(pre_chunks_setup))
|
153 |
+
print("✓ (Setup) Lexical matrices built.")
|
154 |
+
|
155 |
+
print(f"⏳ (Setup) Setting up ChromaDB client at {DB_DIR_APP}...")
|
156 |
+
client_setup = chromadb.PersistentClient(path=str(DB_DIR_APP.resolve()))
|
157 |
+
print(f" → (Setup) Creating collection: {COL_NAME}")
|
158 |
+
try: # Προσπάθεια διαγραφής αν υπάρχει για σίγουρη νέα δημιουργία
|
159 |
+
client_setup.delete_collection(COL_NAME)
|
160 |
+
except: pass
|
161 |
+
col_setup = client_setup.get_or_create_collection(COL_NAME, metadata={"hnsw:space":"cosine"})
|
162 |
+
|
163 |
+
print("⏳ (Setup) Encoding chunks and streaming to ChromaDB...")
|
164 |
+
for start_idx in tq.tqdm(range(0, len(pre_chunks_setup), BATCH_EMB), desc="(Setup) Adding to ChromaDB"):
|
165 |
+
end_idx = min(start_idx + BATCH_EMB, len(pre_chunks_setup))
|
166 |
+
batch_pre_chunks = pre_chunks_setup[start_idx:end_idx]
|
167 |
+
batch_ids = ids_list_setup[start_idx:end_idx]
|
168 |
+
batch_metadatas = metas_setup[start_idx:end_idx]
|
169 |
+
if not batch_pre_chunks: continue
|
170 |
+
batch_embeddings = _cls_embed_setup(batch_pre_chunks, tokenizer_setup, model_setup, bs=BATCH_EMB)
|
171 |
+
col_setup.add(embeddings=batch_embeddings.tolist(), documents=batch_pre_chunks, metadatas=batch_metadatas, ids=batch_ids)
|
172 |
+
|
173 |
+
final_count = col_setup.count()
|
174 |
+
print(f"✓ (Setup) Index built and stored in ChromaDB. Final count: {final_count}")
|
175 |
+
if final_count != len(ids_list_setup):
|
176 |
+
print(f"!!! WARNING (Setup): Mismatch after setup! Expected {len(ids_list_setup)} items, got {final_count}")
|
177 |
+
# return False # Αποφασίζουμε αν αυτό είναι κρίσιμο σφάλμα ή απλή προειδοποίηση
|
178 |
+
|
179 |
+
print(f"💾 (Setup) Saving assets to {ASSETS_DIR_APP}...")
|
180 |
+
joblib.dump(char_vec_setup, ASSETS_DIR_APP / "char_vectorizer.joblib")
|
181 |
+
joblib.dump(word_vec_setup, ASSETS_DIR_APP / "word_vectorizer.joblib")
|
182 |
+
scipy.sparse.save_npz(ASSETS_DIR_APP / "X_char_sparse.npz", X_char_setup)
|
183 |
+
scipy.sparse.save_npz(ASSETS_DIR_APP / "X_word_sparse.npz", X_word_setup)
|
184 |
+
with open(ASSETS_DIR_APP / "pre_chunks.pkl", "wb") as f: pickle.dump(pre_chunks_setup, f)
|
185 |
+
with open(ASSETS_DIR_APP / "raw_chunks.pkl", "wb") as f: pickle.dump(raw_chunks_setup, f)
|
186 |
+
with open(ASSETS_DIR_APP / "ids.pkl", "wb") as f: pickle.dump(ids_list_setup, f)
|
187 |
+
with open(ASSETS_DIR_APP / "metas.pkl", "wb") as f: pickle.dump(metas_setup, f)
|
188 |
+
print("✓ (Setup) Assets saved.")
|
189 |
+
|
190 |
+
del tokenizer_setup, model_setup, docs_json, raw_chunks_setup, pre_chunks_setup, metas_setup, ids_list_setup
|
191 |
+
del char_vec_setup, word_vec_setup, X_char_setup, X_word_setup, client_setup, col_setup
|
192 |
+
if DEVICE == "cuda":
|
193 |
+
torch.cuda.empty_cache()
|
194 |
+
print("🎉 (Setup) Database and assets creation process complete!")
|
195 |
+
return True
|
196 |
+
# ==================================================================
|
197 |
+
|
198 |
+
setup_successful = setup_database_and_assets()
|
199 |
+
|
200 |
+
# ----------------------- PRE-/POST HELPERS (για την εφαρμογή Gradio) ----------------------------
|
201 |
+
def strip_acc(s: str) -> str:
|
202 |
+
return ''.join(ch for ch in unicodedata.normalize('NFD', s)
|
203 |
+
if not unicodedata.combining(ch))
|
204 |
+
|
205 |
+
STOP = {"σχετικο", "σχετικα", "με", "και"}
|
206 |
+
|
207 |
+
def preprocess(txt: str) -> str:
|
208 |
+
txt = strip_acc(txt.lower())
|
209 |
+
txt = re.sub(r"[^a-zα-ω0-9 ]", " ", txt)
|
210 |
+
txt = re.sub(r"\s+", " ", txt).strip()
|
211 |
+
return " ".join(w for w in txt.split() if w not in STOP)
|
212 |
+
|
213 |
+
# cls_embed για την εφαρμογή Gradio (ένα query κάθε φορά)
|
214 |
+
def cls_embed(texts, tokenizer_app, model_app):
|
215 |
+
out = []
|
216 |
+
enc = tokenizer_app(texts, padding=True, truncation=True,
|
217 |
+
max_length=CHUNK_SIZE, return_tensors="pt").to(DEVICE)
|
218 |
+
with torch.no_grad():
|
219 |
+
model_output = model_app(**enc)
|
220 |
+
last_hidden_state = model_output.last_hidden_state
|
221 |
+
cls_embedding = last_hidden_state[:, 0, :]
|
222 |
+
cls_normalized = torch.nn.functional.normalize(cls_embedding, p=2, dim=1)
|
223 |
+
out.append(cls_normalized.cpu())
|
224 |
+
return torch.cat(out).numpy()
|
225 |
+
|
226 |
+
# ---------------------- LOAD MODELS & DATA (Για την εφαρμογή Gradio) --------------------
|
227 |
+
tok = None
|
228 |
+
model = None
|
229 |
+
char_vec = None
|
230 |
+
word_vec = None
|
231 |
+
X_char = None
|
232 |
+
X_word = None
|
233 |
+
pre_chunks = None
|
234 |
+
raw_chunks = None
|
235 |
+
ids = None
|
236 |
+
metas = None
|
237 |
+
col = None
|
238 |
+
|
239 |
+
if setup_successful:
|
240 |
+
print(f"⏳ Loading Model ({MODEL_NAME}) and Tokenizer for Gradio App...")
|
241 |
+
try:
|
242 |
+
tok = AutoTokenizer.from_pretrained(MODEL_NAME)
|
243 |
+
model = AutoModel.from_pretrained(MODEL_NAME).to(DEVICE).eval()
|
244 |
+
print("✓ Model and tokenizer loaded for Gradio App.")
|
245 |
+
except Exception as e:
|
246 |
+
print(f"CRITICAL ERROR loading model/tokenizer for Gradio App: {e}")
|
247 |
+
setup_successful = False
|
248 |
+
|
249 |
+
if setup_successful:
|
250 |
+
print(f"⏳ Loading TF-IDF/Assets from {ASSETS_DIR_APP} for Gradio App...")
|
251 |
+
try:
|
252 |
+
char_vec = joblib.load(ASSETS_DIR_APP / "char_vectorizer.joblib")
|
253 |
+
word_vec = joblib.load(ASSETS_DIR_APP / "word_vectorizer.joblib")
|
254 |
+
X_char = scipy.sparse.load_npz(ASSETS_DIR_APP / "X_char_sparse.npz")
|
255 |
+
X_word = scipy.sparse.load_npz(ASSETS_DIR_APP / "X_word_sparse.npz")
|
256 |
+
with open(ASSETS_DIR_APP / "pre_chunks.pkl", "rb") as f: pre_chunks = pickle.load(f)
|
257 |
+
with open(ASSETS_DIR_APP / "raw_chunks.pkl", "rb") as f: raw_chunks = pickle.load(f)
|
258 |
+
with open(ASSETS_DIR_APP / "ids.pkl", "rb") as f: ids = pickle.load(f)
|
259 |
+
with open(ASSETS_DIR_APP / "metas.pkl", "rb") as f: metas = pickle.load(f)
|
260 |
+
print("✓ TF-IDF/Assets loaded for Gradio App.")
|
261 |
+
except Exception as e:
|
262 |
+
print(f"CRITICAL ERROR loading TF-IDF/Assets for Gradio App: {e}")
|
263 |
+
setup_successful = False
|
264 |
+
|
265 |
+
if setup_successful:
|
266 |
+
print(f"⏳ Connecting to ChromaDB at {DB_DIR_APP} for Gradio App...")
|
267 |
+
try:
|
268 |
+
client = chromadb.PersistentClient(path=str(DB_DIR_APP.resolve()))
|
269 |
+
col = client.get_collection(COL_NAME) # Αν δεν υπάρχει μετά το setup, εδώ θα γίνει σφάλμα.
|
270 |
+
print(f"✓ Connected to ChromaDB. Collection '{COL_NAME}' count: {col.count()}")
|
271 |
+
if col.count() == 0 and len(ids) > 0: # Αν υπάρχουν ids αλλά η βάση είναι άδεια
|
272 |
+
print(f"!!! CRITICAL WARNING: ChromaDB collection '{COL_NAME}' is EMPTY at {DB_DIR_APP} but assets were loaded. Setup might have failed to populate DB correctly.")
|
273 |
+
setup_successful = False
|
274 |
+
except Exception as e:
|
275 |
+
print(f"CRITICAL ERROR connecting to ChromaDB or getting collection for Gradio App: {e}")
|
276 |
+
setup_successful = False
|
277 |
+
else:
|
278 |
+
print("!!! Setup process failed or was skipped. Gradio app will not function correctly. !!!")
|
279 |
+
|
280 |
+
# ---------------------- HYBRID SEARCH (Κύρια Λογική) ---
|
281 |
+
def hybrid_search_gradio(query, k=5):
|
282 |
+
if not setup_successful or not ids or not col or not model or not tok:
|
283 |
+
return "Σφάλμα: Η εφαρμογή δεν αρχικοποιήθηκε σωστά. Τα δεδομένα ή το μοντέλο δεν φορτώθηκαν. Ελέγξτε τα logs εκκίνησης."
|
284 |
+
if not query.strip():
|
285 |
+
return "Παρακαλώ εισάγετε μια ερώτηση."
|
286 |
+
|
287 |
+
q_pre = preprocess(query)
|
288 |
+
words = q_pre.split()
|
289 |
+
alpha = ALPHA_LONGQ if len(words) > 30 else ALPHA_BASE
|
290 |
+
exact_ids_set = {ids[i] for i, t in enumerate(pre_chunks) if q_pre in t}
|
291 |
+
q_emb_np = cls_embed([q_pre], tok, model)
|
292 |
+
q_emb_list = q_emb_np.tolist()
|
293 |
+
|
294 |
+
try:
|
295 |
+
sem_results = col.query(query_embeddings=q_emb_list, n_results=min(k * 30, len(ids)), include=["distances"])
|
296 |
+
except Exception as e:
|
297 |
+
# Εκτύπωση του σφάλματος στα logs του server για διάγνωση
|
298 |
+
print(f"ERROR during ChromaDB query in hybrid_search_gradio: {type(e).__name__}: {e}")
|
299 |
+
return "Σφάλμα κατά την σημασιολογική αναζήτηση. Επικοινωνήστε με τον διαχειριστή."
|
300 |
+
|
301 |
+
sem_sims = {doc_id: 1 - dist for doc_id, dist in zip(sem_results["ids"][0], sem_results["distances"][0])}
|
302 |
+
q_char_sparse = char_vec.transform([q_pre])
|
303 |
+
q_char_normalized = sk_normalize(q_char_sparse)
|
304 |
+
char_sim_scores = (q_char_normalized @ X_char.T).toarray().flatten()
|
305 |
+
q_word_sparse = word_vec.transform([q_pre])
|
306 |
+
q_word_normalized = sk_normalize(q_word_sparse)
|
307 |
+
word_sim_scores = (q_word_normalized @ X_word.T).toarray().flatten()
|
308 |
+
lex_sims = {}
|
309 |
+
for idx, (c_score, w_score) in enumerate(zip(char_sim_scores, word_sim_scores)):
|
310 |
+
if c_score > 0 or w_score > 0:
|
311 |
+
if idx < len(ids): lex_sims[ids[idx]] = 0.85 * c_score + 0.15 * w_score
|
312 |
+
else: print(f"Warning (hybrid_search): Lexical score index {idx} out of bounds for ids list (len: {len(ids)}).")
|
313 |
+
|
314 |
+
all_chunk_ids_set = set(sem_sims.keys()) | set(lex_sims.keys()) | exact_ids_set
|
315 |
+
scored = []
|
316 |
+
for chunk_id_key in all_chunk_ids_set:
|
317 |
+
s = alpha * sem_sims.get(chunk_id_key, 0.0) + (1 - alpha) * lex_sims.get(chunk_id_key, 0.0)
|
318 |
+
if chunk_id_key in exact_ids_set: s = 1.0
|
319 |
+
scored.append((chunk_id_key, s))
|
320 |
+
scored.sort(key=lambda x: x[1], reverse=True)
|
321 |
+
hits_output = []
|
322 |
+
seen_doc_main_ids = set()
|
323 |
+
for chunk_id_val, score_val in scored:
|
324 |
+
try: idx_in_lists = ids.index(chunk_id_val)
|
325 |
+
except ValueError: print(f"Warning (hybrid_search): chunk_id '{chunk_id_val}' not found in loaded ids. Skipping."); continue
|
326 |
+
doc_meta = metas[idx_in_lists]
|
327 |
+
doc_main_id = doc_meta['id']
|
328 |
+
if doc_main_id in seen_doc_main_ids: continue
|
329 |
+
original_url_from_meta = doc_meta.get('url', '#')
|
330 |
+
pdf_gcs_url = "#"
|
331 |
+
pdf_filename_display = "N/A"
|
332 |
+
if original_url_from_meta and original_url_from_meta != '#':
|
333 |
+
pdf_filename_extracted = os.path.basename(original_url_from_meta)
|
334 |
+
if pdf_filename_extracted and pdf_filename_extracted.lower().endswith(".pdf"):
|
335 |
+
pdf_gcs_url = f"{GCS_PUBLIC_URL_PREFIX}{pdf_filename_extracted}"
|
336 |
+
pdf_filename_display = pdf_filename_extracted
|
337 |
+
elif pdf_filename_extracted: pdf_filename_display = "Source is not a PDF"
|
338 |
+
# else: pdf_filename_display = "No source URL" # This case is covered by initialization
|
339 |
+
# else: pdf_filename_display = "No source URL" # This case is covered by initialization
|
340 |
+
|
341 |
+
hits_output.append({
|
342 |
+
"score": score_val, "title": doc_meta.get('title', 'N/A'),
|
343 |
+
"snippet": raw_chunks[idx_in_lists][:500] + " ...",
|
344 |
+
"original_url_meta": original_url_from_meta, "pdf_serve_url": pdf_gcs_url,
|
345 |
+
"pdf_filename_display": pdf_filename_display
|
346 |
+
})
|
347 |
+
seen_doc_main_ids.add(doc_main_id)
|
348 |
+
if len(hits_output) >= k: break
|
349 |
+
if not hits_output: return "Δεν βρέθηκαν σχετικά αποτελέσματα."
|
350 |
+
output_md = f"Βρέθηκαν **{len(hits_output)}** σχετικά αποτελέσματα:\n\n"
|
351 |
+
for hit in hits_output:
|
352 |
+
output_md += f"### {hit['title']} (Score: {hit['score']:.3f})\n"
|
353 |
+
snippet_wrapped = textwrap.fill(hit['snippet'].replace("\n", " "), width=100)
|
354 |
+
output_md += f"**Απόσπασμα:** {snippet_wrapped}\n"
|
355 |
+
if hit['pdf_serve_url'] and hit['pdf_serve_url'] != '#':
|
356 |
+
output_md += f"**Πηγή (PDF):** <a href='{hit['pdf_serve_url']}' target='_blank'>{hit['pdf_filename_display']}</a>\n"
|
357 |
+
elif hit['original_url_meta'] and hit['original_url_meta'] != '#':
|
358 |
+
output_md += f"**Πηγή (αρχικό από metadata):** [{hit['original_url_meta']}]({hit['original_url_meta']})\n"
|
359 |
+
output_md += "---\n"
|
360 |
+
return output_md
|
361 |
+
|
362 |
+
# ---------------------- GRADIO INTERFACE -----------------------------------
|
363 |
+
print("🚀 Launching Gradio Interface for ChatbotVol107...")
|
364 |
+
iface = gr.Interface(
|
365 |
+
fn=hybrid_search_gradio,
|
366 |
+
inputs=gr.Textbox(lines=3, placeholder="Γράψε την ερώτησή σου εδώ...", label=f"Ερώτηση προς τον βοηθό (Μοντέλο: {MODEL_NAME.split('/')[-1]}):"),
|
367 |
+
outputs=gr.Markdown(label="Απαντήσεις από τα έγγραφα:", rtl=False, sanitize_html=False),
|
368 |
+
title=f"🏛️ Ελληνικό Chatbot Υβριδικής Αναζήτησης (ChatbotVol107 - {MODEL_NAME.split('/')[-1]})",
|
369 |
+
description=(f"Πληκτρολογήστε την ερώτησή σας για αναζήτηση. Χρησιμοποιεί το μοντέλο: {MODEL_NAME}.\n"
|
370 |
+
"Τα PDF ανοίγουν από Google Cloud Storage σε νέα καρτέλα."),
|
371 |
+
allow_flagging="never",
|
372 |
+
examples=[
|
373 |
+
["Τεχνολογίας τροφίμων;", 5],
|
374 |
+
["Αμπελουργίας και της οινολογίας", 3],
|
375 |
+
["Ποιες θέσεις αφορούν διδάσκοντες μερικής απασχόλησης στο Τμήμα Νοσηλευτικής του Πανεπιστημίου Ιωαννίνων;", 5]
|
376 |
+
],
|
377 |
+
)
|
378 |
+
|
379 |
+
if __name__ == '__main__':
|
380 |
+
# Το allowed_paths δεν είναι απαραίτητο αν δεν εξυπηρετούνται άλλα τοπικά στατικά αρχεία.
|
381 |
+
iface.launch()
|