File size: 31,167 Bytes
95567a6 3a67ea1 95567a6 3a67ea1 95567a6 65d6ffc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
import gradio as gr
import torch
import unicodedata
import re
import numpy as np
from pathlib import Path
from transformers import AutoTokenizer, AutoModel # AutoModelForCausalLM μπορεί να είναι πιο κατάλληλο για Instruct μοντέλα, αλλά για embeddings το AutoModel συχνά αρκεί.
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.preprocessing import normalize as sk_normalize
import chromadb
import joblib
import pickle
import scipy.sparse
import textwrap
import os
import json # Για το διάβασμα του JSON κατά το setup
import tqdm.auto as tq # Για progress bars κατά το setup
# --------------------------- CONFIG για ChatbotVol108 (Meltemi) -----------------------------------
# --- Ρυθμίσεις Μοντέλου και Βάσης Δεδομένων ---
MODEL_NAME = "ilsp/Meltemi-7B-Instruct-v1.5" # ΝΕΟ ΜΟΝΤΕΛΟ
PERSISTENT_STORAGE_ROOT = Path("/data") # Για Hugging Face Spaces Persistent Storage (ή τοπικό path)
# Προσαρμοσμένα paths για το νέο project και μοντέλο
DB_DIR_APP = PERSISTENT_STORAGE_ROOT / "chroma_db_ChatbotVol108_Meltemi"
COL_NAME = "collection_chatbotvol108_meltemi"
ASSETS_DIR_APP = PERSISTENT_STORAGE_ROOT / "assets_ChatbotVol108_Meltemi"
# Το dataset14.json πρέπει να υπάρχει στο root του Hugging Face Space repository σας
DATA_PATH_FOR_SETUP = "./dataset14.json"
# ---------------------------------------------
# --- Ρυθμίσεις για Google Cloud Storage για τα PDF links ---
GCS_BUCKET_NAME = "chatbotthesisihu" # Το δικό σας GCS Bucket Name
GCS_PUBLIC_URL_PREFIX = f"https://storage.googleapis.com/{GCS_BUCKET_NAME}/"
# -------------------------------------------------------------
# --- Παράμετροι Αναζήτησης και Μοντέλου ---
CHUNK_SIZE = 512 # Μπορεί να αυξηθεί αν το context window του Meltemi είναι μεγαλύτερο, αλλά προσέξτε τη VRAM
CHUNK_OVERLAP = 40
BATCH_EMB = 8 # Μειωμένο από 32. Προσαρμόστε ανάλογα με τη VRAM σας. Για 7B μοντέλα, ίσως χρειαστεί και μικρότερο (π.χ. 4 ή 8).
ALPHA_BASE = 0.2 # Αυτές οι τιμές alpha ήταν βελτιστοποιημένες για το BERT. Μπορεί να χρειαστούν νέα βελτιστοποίηση.
ALPHA_LONGQ = 0.35
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Running ChatbotVol108 on device: {DEVICE}")
print(f"Using model: {MODEL_NAME}")
if DEVICE == "cuda":
print(f"CUDA Device Name: {torch.cuda.get_device_name(0)}")
print(f"CUDA Device Capability: {torch.cuda.get_device_capability(0)}")
# === ΛΟΓΙΚΗ ΔΗΜΙΟΥΡΓΙΑΣ ΒΑΣΗΣ ΚΑΙ ASSETS (Αν δεν υπάρχουν) ===
def setup_database_and_assets():
print("Checking if database and assets need to be created for ChatbotVol108 (Meltemi)...")
run_setup = True
if DB_DIR_APP.exists() and ASSETS_DIR_APP.exists() and (ASSETS_DIR_APP / "ids.pkl").exists():
try:
client_check = chromadb.PersistentClient(path=str(DB_DIR_APP.resolve()))
collection_check = client_check.get_collection(name=COL_NAME)
if collection_check.count() > 0:
print("✓ Database and assets appear to exist and collection is populated. Skipping setup.")
run_setup = False
else:
print("Collection exists but is empty. Proceeding with setup.")
if DB_DIR_APP.exists():
import shutil
print(f"Attempting to clean up existing empty/corrupt DB directory: {DB_DIR_APP}")
shutil.rmtree(DB_DIR_APP)
except Exception as e_check:
print(f"Database or collection check failed (Error: {e_check}). Proceeding with setup.")
if DB_DIR_APP.exists():
import shutil
print(f"Attempting to clean up existing corrupt DB directory: {DB_DIR_APP}")
shutil.rmtree(DB_DIR_APP)
if not run_setup:
return True
print(f"!!! Database/Assets not found or incomplete for ChatbotVol108 (Meltemi). Starting setup process...")
print(f"!!! This may take a very long time, especially on the first run with Meltemi-7B !!!")
ASSETS_DIR_APP.mkdir(parents=True, exist_ok=True)
DB_DIR_APP.mkdir(parents=True, exist_ok=True)
def _strip_acc_setup(s:str)->str: return ''.join(ch for ch in unicodedata.normalize('NFD', s) if not unicodedata.combining(ch))
_STOP_SETUP = {"σχετικο","σχετικά","με","και"}
def _preprocess_setup(txt:str)->str:
txt = _strip_acc_setup(txt.lower())
txt = re.sub(r"[^a-zα-ω0-9 ]", " ", txt)
txt = re.sub(r"\s+", " ", txt).strip()
return " ".join(w for w in txt.split() if w not in _STOP_SETUP)
def _chunk_text_setup(text, tokenizer_setup):
# Η λογική chunking παραμένει ίδια, βασίζεται στο tokenizer και CHUNK_SIZE
token_ids = tokenizer_setup.encode(text, add_special_tokens=False)
if len(token_ids) <= (CHUNK_SIZE - tokenizer_setup.model_max_length + tokenizer_setup.max_len_single_sentence): # Προσαρμογή για special tokens αν υπάρχουν
return [text]
ids_with_special_tokens = tokenizer_setup(text, truncation=False, padding=False)["input_ids"]
effective_chunk_size = CHUNK_SIZE
step = effective_chunk_size - CHUNK_OVERLAP
chunks = []
for i in range(0, len(ids_with_special_tokens), step):
current_chunk_ids = ids_with_special_tokens[i:i+effective_chunk_size]
if not current_chunk_ids: break
if len(chunks) > 0 and len(current_chunk_ids) < CHUNK_OVERLAP:
if len(ids_with_special_tokens) - i < effective_chunk_size: pass
else: break
decoded_chunk = tokenizer_setup.decode(current_chunk_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True).strip()
if decoded_chunk: chunks.append(decoded_chunk)
return chunks if chunks else [text]
# ΝΕΑ ΣΥΝΑΡΤΗΣΗ ΓΙΑ MEAN POOLING EMBEDDINGS (κατάλληλη για decoder-only models όπως το Meltemi)
def _mean_pooling_embed_setup(texts, tokenizer_setup, model_setup, device_setup, bs=BATCH_EMB, max_length_embed=CHUNK_SIZE):
out_embeddings = []
model_setup.eval() # Βεβαιωθείτε ότι το μοντέλο είναι σε eval mode
for i in tq.tqdm(range(0, len(texts), bs), desc="Embedding texts for DB setup (Mean Pooling)"):
batch_texts = texts[i:i+bs]
# return_attention_mask=True είναι σημαντικό για το mean pooling
enc = tokenizer_setup(batch_texts, padding=True, truncation=True, max_length=max_length_embed, return_tensors="pt", return_attention_mask=True).to(device_setup)
with torch.no_grad():
model_output = model_setup(**enc)
last_hidden_state = model_output.last_hidden_state
attention_mask = enc['attention_mask']
# Mean Pooling:
input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)
sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9) # Αποφυγή διαίρεσης με μηδέν
mean_pooled = sum_embeddings / sum_mask
normalized_embeddings = torch.nn.functional.normalize(mean_pooled, p=2, dim=1)
out_embeddings.append(normalized_embeddings.cpu())
return torch.cat(out_embeddings).numpy()
print(f"⏳ (Setup) Loading Model ({MODEL_NAME}) and Tokenizer...")
# Φόρτωση του Meltemi με torch_dtype=torch.float16 για εξοικονόμηση VRAM και trust_remote_code=True
# Εάν αντιμετωπίζετε προβλήματα μνήμης, εξετάστε:
# from transformers import BitsAndBytesConfig
# quantization_config = BitsAndBytesConfig(load_in_8bit=True) # ή load_in_4bit=True
# model_setup = AutoModel.from_pretrained(MODEL_NAME, device_map="auto", torch_dtype=torch.float16, trust_remote_code=True, quantization_config=quantization_config)
# και προσθέστε 'bitsandbytes' στα requirements.txt
try:
tokenizer_setup = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
# Αν το tokenizer δεν έχει padding token, ορίστε ένα:
if tokenizer_setup.pad_token is None:
tokenizer_setup.pad_token = tokenizer_setup.eos_token # Συνηθισμένη πρακτική για Causal LMs
print("Tokenizer `pad_token` was None, set to `eos_token`.")
model_setup = AutoModel.from_pretrained(
MODEL_NAME,
torch_dtype=torch.float16, # Σημαντικό για μεγάλα μοντέλα!
trust_remote_code=True, # Απαιτείται για ορισμένα μοντέλα από το Hub
# device_map="auto" # Χρησιμοποιήστε το αν έχετε πολλαπλές GPUs ή για καλύτερη διαχείριση μνήμης με accelerate
).to(DEVICE).eval() # .eval() είναι σημαντικό
print("✓ (Setup) Model and Tokenizer loaded.")
except Exception as e:
print(f"!!! CRITICAL SETUP ERROR: Could not load model or tokenizer: {e}")
print("!!! Make sure you have enough VRAM, `trust_remote_code=True` is set, and you are logged in to Hugging Face if needed.")
return False
print(f"⏳ (Setup) Reading & chunking JSON data from {DATA_PATH_FOR_SETUP}...")
if not Path(DATA_PATH_FOR_SETUP).exists():
print(f"!!! CRITICAL SETUP ERROR: Dataset file {DATA_PATH_FOR_SETUP} not found! Please upload it.")
return False
with open(DATA_PATH_FOR_SETUP, encoding="utf-8") as f: docs_json = json.load(f)
raw_chunks_setup, pre_chunks_setup, metas_setup, ids_list_setup = [], [], [], []
for d_setup in tq.tqdm(docs_json, desc="(Setup) Processing documents"):
doc_text = d_setup.get("text")
if not doc_text: continue
chunked_doc_texts = _chunk_text_setup(doc_text, tokenizer_setup)
if not chunked_doc_texts: continue
for idx, chunk in enumerate(chunked_doc_texts):
if not chunk.strip(): continue
raw_chunks_setup.append(chunk)
pre_chunks_setup.append(_preprocess_setup(chunk)) # Το preprocess παραμένει το ίδιο για lexical search
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)})
ids_list_setup.append(f'{d_setup["id"]}_c{idx+1}')
print(f" → (Setup) Total chunks created: {len(raw_chunks_setup):,}")
if not raw_chunks_setup:
print("!!! CRITICAL SETUP ERROR: No chunks were created from the dataset.")
return False
print("⏳ (Setup) Building lexical matrices (TF-IDF)...") # Αυτό παραμένει ίδιο
char_vec_setup = HashingVectorizer(analyzer="char_wb", ngram_range=(2,5), n_features=2**20, norm=None, alternate_sign=False, binary=True)
word_vec_setup = HashingVectorizer(analyzer="word", ngram_range=(1,2), n_features=2**19, norm=None, alternate_sign=False, binary=True)
X_char_setup = sk_normalize(char_vec_setup.fit_transform(pre_chunks_setup))
X_word_setup = sk_normalize(word_vec_setup.fit_transform(pre_chunks_setup))
print("✓ (Setup) Lexical matrices built.")
print(f"⏳ (Setup) Setting up ChromaDB client at {DB_DIR_APP}...")
client_setup = chromadb.PersistentClient(path=str(DB_DIR_APP.resolve()))
print(f" → (Setup) Creating collection: {COL_NAME}")
try: client_setup.delete_collection(COL_NAME)
except: pass
col_setup = client_setup.get_or_create_collection(COL_NAME, metadata={"hnsw:space":"cosine"}) # cosine είναι καλή επιλογή για normalized embeddings
print("⏳ (Setup) Encoding chunks (using mean pooling) and streaming to ChromaDB...")
# Χρήση της νέας συνάρτησης embedding
# Τα pre_chunks_setup είναι τα κείμενα που θα γίνουν embed. Για το Meltemi, είναι καλύτερα να χρησιμοποιήσουμε τα raw_chunks_setup (ή τα pre_chunks_setup αν η προεπεξεργασία είναι ελαφριά)
# Εδώ θα χρησιμοποιήσω τα raw_chunks_setup για τα embeddings, καθώς τα LLMs συχνά επωφελούνται από το πλήρες, μη επεξεργασμένο κείμενο.
# Αν τα pre_chunks είναι πολύ διαφορετικά, μπορεί να επηρεάσει την ποιότητα. Για τώρα, ας δοκιμάσουμε με raw_chunks.
# ΣΗΜΑΝΤΙΚΟ: Βεβαιωθείτε ότι τα embeddings αντιστοιχούν στα 'documents' που αποθηκεύετε.
# Εάν τα 'documents' στη Chroma είναι τα pre_chunks, τότε τα embeddings πρέπει να είναι από τα pre_chunks.
# Εδώ, το col_setup.add() χρησιμοποιεί batch_pre_chunks ως documents, οπότε και τα embeddings πρέπει να είναι από αυτά.
# Δημιουργία embeddings σε batches
all_embeddings_list = []
# Χρήση της _mean_pooling_embed_setup. Τα κείμενα για embedding πρέπει να είναι τα ίδια που θα αποθηκευτούν ως "documents" στη βάση.
# Ο αρχικός κώδικας έκανε embed τα pre_chunks. Θα διατηρήσουμε αυτό για συνέπεια, αλλά σημειώστε ότι για LLMs, τα raw chunks μπορεί να είναι καλύτερα.
chunk_embeddings_np = _mean_pooling_embed_setup(pre_chunks_setup, tokenizer_setup, model_setup, DEVICE, bs=BATCH_EMB, max_length_embed=CHUNK_SIZE)
print(f" → (Setup) Generated {chunk_embeddings_np.shape[0]} embeddings. Adding to ChromaDB in batches...")
# Προσθήκη στη ChromaDB σε μικρότερα batches για να αποφευχθούν προβλήματα με μεγάλα payloads
db_add_batch_size = 5000 # Μπορείτε να προσαρμόσετε αυτό το batch size
for i in tq.tqdm(range(0, len(ids_list_setup), db_add_batch_size), desc="(Setup) Adding to ChromaDB"):
start_idx_db = i
end_idx_db = min(i + db_add_batch_size, len(ids_list_setup))
batch_ids_db = ids_list_setup[start_idx_db:end_idx_db]
batch_embeddings_db = chunk_embeddings_np[start_idx_db:end_idx_db].tolist()
batch_documents_db = pre_chunks_setup[start_idx_db:end_idx_db] # Αποθηκεύουμε τα pre_chunks
batch_metadatas_db = metas_setup[start_idx_db:end_idx_db]
if not batch_ids_db: continue
col_setup.add(
embeddings=batch_embeddings_db,
documents=batch_documents_db, # Αυτά είναι τα κείμενα που αντιστοιχούν στα embeddings
metadatas=batch_metadatas_db,
ids=batch_ids_db
)
final_count = col_setup.count()
print(f"✓ (Setup) Index built and stored in ChromaDB. Final count: {final_count}")
if final_count != len(ids_list_setup):
print(f"!!! WARNING (Setup): Mismatch after setup! Expected {len(ids_list_setup)} items, got {final_count}")
print(f"💾 (Setup) Saving assets to {ASSETS_DIR_APP}...")
joblib.dump(char_vec_setup, ASSETS_DIR_APP / "char_vectorizer.joblib")
joblib.dump(word_vec_setup, ASSETS_DIR_APP / "word_vectorizer.joblib")
scipy.sparse.save_npz(ASSETS_DIR_APP / "X_char_sparse.npz", X_char_setup)
scipy.sparse.save_npz(ASSETS_DIR_APP / "X_word_sparse.npz", X_word_setup)
with open(ASSETS_DIR_APP / "pre_chunks.pkl", "wb") as f: pickle.dump(pre_chunks_setup, f)
with open(ASSETS_DIR_APP / "raw_chunks.pkl", "wb") as f: pickle.dump(raw_chunks_setup, f)
with open(ASSETS_DIR_APP / "ids.pkl", "wb") as f: pickle.dump(ids_list_setup, f)
with open(ASSETS_DIR_APP / "metas.pkl", "wb") as f: pickle.dump(metas_setup, f)
print("✓ (Setup) Assets saved.")
del tokenizer_setup, model_setup, docs_json, raw_chunks_setup, pre_chunks_setup, metas_setup, ids_list_setup, chunk_embeddings_np
del char_vec_setup, word_vec_setup, X_char_setup, X_word_setup, client_setup, col_setup
if DEVICE == "cuda":
torch.cuda.empty_cache()
print("🎉 (Setup) Database and assets creation process for ChatbotVol108 (Meltemi) complete!")
return True
# ==================================================================
setup_successful = setup_database_and_assets()
# ----------------------- PRE-/POST HELPERS (για την εφαρμογή Gradio) ----------------------------
# Αυτά παραμένουν ίδια καθώς αφορούν το lexical κομμάτι και το string normalization
def strip_acc(s: str) -> str:
return ''.join(ch for ch in unicodedata.normalize('NFD', s)
if not unicodedata.combining(ch))
STOP = {"σχετικο", "σχετικα", "με", "και"}
def preprocess(txt: str) -> str:
txt = strip_acc(txt.lower())
txt = re.sub(r"[^a-zα-ω0-9 ]", " ", txt)
txt = re.sub(r"\s+", " ", txt).strip()
return " ".join(w for w in txt.split() if w not in STOP)
# ΝΕΑ ΣΥΝΑΡΤΗΣΗ ΓΙΑ MEAN POOLING EMBEDDINGS ΓΙΑ ΤΟ GRADIO APP
def mean_pooling_embed_app(texts, tokenizer_app, model_app, device_app, max_length_embed=CHUNK_SIZE):
# Βεβαιωθείτε ότι το μοντέλο είναι σε eval mode (αν και θα έπρεπε ήδη να είναι)
model_app.eval()
# texts εδώ είναι μια λίστα με ένα string (το query)
enc = tokenizer_app(texts, padding=True, truncation=True, max_length=max_length_embed, return_tensors="pt", return_attention_mask=True).to(device_app)
with torch.no_grad():
model_output = model_app(**enc)
last_hidden_state = model_output.last_hidden_state
attention_mask = enc['attention_mask']
input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()
sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)
sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)
mean_pooled = sum_embeddings / sum_mask
normalized_embeddings = torch.nn.functional.normalize(mean_pooled, p=2, dim=1)
return normalized_embeddings.cpu().numpy()
# ---------------------- LOAD MODELS & DATA (Για την εφαρμογή Gradio) --------------------
tok_app = None # Μετονομασία για σαφήνεια
model_app = None # Μετονομασία για σαφήνεια
char_vec = None
word_vec = None
X_char = None
X_word = None
pre_chunks_app = None # Μετονομασία
raw_chunks_app = None # Μετονομασία
ids_app = None # Μετονομασία
metas_app = None # Μετονομασία
col_app = None # Μετονομασία
if setup_successful:
print(f"⏳ Loading Model ({MODEL_NAME}) and Tokenizer for Gradio App (ChatbotVol108)...")
try:
tok_app = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
if tok_app.pad_token is None:
tok_app.pad_token = tok_app.eos_token
print("App Tokenizer `pad_token` was None, set to `eos_token`.")
# Φόρτωση με τις ίδιες παραμέτρους όπως στο setup
model_app = AutoModel.from_pretrained(
MODEL_NAME,
torch_dtype=torch.float16,
trust_remote_code=True,
# device_map="auto" # Εξετάστε το για καλύτερη διαχείριση
).to(DEVICE).eval()
print("✓ Model and tokenizer loaded for Gradio App.")
except Exception as e:
print(f"CRITICAL ERROR loading model/tokenizer for Gradio App: {e}")
setup_successful = False
if setup_successful:
print(f"⏳ Loading TF-IDF/Assets from {ASSETS_DIR_APP} for Gradio App...")
try:
char_vec = joblib.load(ASSETS_DIR_APP / "char_vectorizer.joblib")
word_vec = joblib.load(ASSETS_DIR_APP / "word_vectorizer.joblib")
X_char = scipy.sparse.load_npz(ASSETS_DIR_APP / "X_char_sparse.npz")
X_word = scipy.sparse.load_npz(ASSETS_DIR_APP / "X_word_sparse.npz")
with open(ASSETS_DIR_APP / "pre_chunks.pkl", "rb") as f: pre_chunks_app = pickle.load(f)
with open(ASSETS_DIR_APP / "raw_chunks.pkl", "rb") as f: raw_chunks_app = pickle.load(f)
with open(ASSETS_DIR_APP / "ids.pkl", "rb") as f: ids_app = pickle.load(f)
with open(ASSETS_DIR_APP / "metas.pkl", "rb") as f: metas_app = pickle.load(f)
print("✓ TF-IDF/Assets loaded for Gradio App.")
except Exception as e:
print(f"CRITICAL ERROR loading TF-IDF/Assets for Gradio App: {e}")
setup_successful = False
if setup_successful:
print(f"⏳ Connecting to ChromaDB at {DB_DIR_APP} for Gradio App...")
try:
client_app = chromadb.PersistentClient(path=str(DB_DIR_APP.resolve()))
col_app = client_app.get_collection(COL_NAME)
print(f"✓ Connected to ChromaDB. Collection '{COL_NAME}' count: {col_app.count()}")
if col_app.count() == 0 and (ids_app and len(ids_app) > 0):
print(f"!!! CRITICAL WARNING: ChromaDB collection '{COL_NAME}' is EMPTY but assets were loaded. Setup might have failed to populate DB correctly.")
setup_successful = False
except Exception as e:
print(f"CRITICAL ERROR connecting to ChromaDB or getting collection for Gradio App: {e}")
setup_successful = False
else:
print("!!! Setup process failed or was skipped for ChatbotVol108. Gradio app will not function correctly. !!!")
# ---------------------- HYBRID SEARCH (Κύρια Λογική) ---
def hybrid_search_gradio(query, k=5):
if not setup_successful or not ids_app or not col_app or not model_app or not tok_app or not raw_chunks_app or not metas_app or not pre_chunks_app: # Ελέγχουμε και τα raw_chunks, metas
return "Σφάλμα: Η εφαρμογή δεν αρχικοποιήθηκε σωστά. Τα δεδομένα ή το μοντέλο δεν φορτώθηκαν. Ελέγξτε τα logs εκκίνησης."
if not query.strip():
return "Παρακαλώ εισάγετε μια ερώτηση."
q_pre = preprocess(query) # Για το lexical κομμάτι
words = q_pre.split()
alpha = ALPHA_LONGQ if len(words) > 30 else ALPHA_BASE # Οι τιμές alpha μπορεί να χρειάζονται tuning για το Meltemi
# Semantic Search Part (Meltemi Embeddings)
# Χρήση της νέας συνάρτησης mean_pooling_embed_app
# Το query για το embedding πρέπει να είναι το raw query ή μια ελαφρώς καθαρισμένη έκδοση, όχι απαραίτητα το q_pre που είναι για lexical.
# Εδώ, για συνέπεια με το πώς δημιουργήθηκαν τα embeddings των chunks (από pre_chunks_setup), θα κάνουμε embed το q_pre.
q_emb_np = mean_pooling_embed_app([q_pre], tok_app, model_app, DEVICE, max_length_embed=CHUNK_SIZE) # Το query είναι το q_pre
q_emb_list = q_emb_np.tolist()
try:
# Το n_results για το semantic search μπορεί να είναι μεγαλύτερο για να δώσει περισσότερες επιλογές στο re-ranking
sem_results_count = min(k * 30, len(ids_app)) if ids_app else k * 30
if sem_results_count <=0: sem_results_count = k # Fallback
sem_results = col_app.query(query_embeddings=q_emb_list, n_results=sem_results_count, include=["distances"])
except Exception as e:
print(f"ERROR during ChromaDB query in hybrid_search_gradio: {type(e).__name__}: {e}")
return "Σφάλμα κατά την σημασιολογική αναζήτηση. Επικοινωνήστε με τον διαχειριστή."
sem_sims = {doc_id: 1 - dist for doc_id, dist in zip(sem_results["ids"][0], sem_results["distances"][0])}
# Lexical Search Part (TF-IDF - παραμένει ίδιο)
# Το `exact_ids_set` πρέπει να ψάχνει στα `pre_chunks_app`
exact_ids_set = {ids_app[i] for i, t in enumerate(pre_chunks_app) if q_pre in t}
q_char_sparse = char_vec.transform([q_pre])
q_char_normalized = sk_normalize(q_char_sparse)
char_sim_scores = (q_char_normalized @ X_char.T).toarray().flatten()
q_word_sparse = word_vec.transform([q_pre])
q_word_normalized = sk_normalize(q_word_sparse)
word_sim_scores = (q_word_normalized @ X_word.T).toarray().flatten()
lex_sims = {}
for idx, (c_score, w_score) in enumerate(zip(char_sim_scores, word_sim_scores)):
if c_score > 0 or w_score > 0:
if idx < len(ids_app): lex_sims[ids_app[idx]] = 0.85 * c_score + 0.15 * w_score # Βαθμολόγηση lexical
else: print(f"Warning (hybrid_search): Lexical score index {idx} out of bounds for ids_app list (len: {len(ids_app)}).")
# Hybrid Re-ranking
all_chunk_ids_set = set(sem_sims.keys()) | set(lex_sims.keys()) | exact_ids_set
scored = []
for chunk_id_key in all_chunk_ids_set:
s = alpha * sem_sims.get(chunk_id_key, 0.0) + (1 - alpha) * lex_sims.get(chunk_id_key, 0.0)
if chunk_id_key in exact_ids_set: s = 1.0 # Boost για ακριβή ταίριασμα
scored.append((chunk_id_key, s))
scored.sort(key=lambda x: x[1], reverse=True)
# Format Output
hits_output = []
seen_doc_main_ids = set()
for chunk_id_val, score_val in scored:
try:
idx_in_lists = ids_app.index(chunk_id_val)
except ValueError:
print(f"Warning (hybrid_search): chunk_id '{chunk_id_val}' not found in loaded ids_app. Skipping.")
continue
doc_meta = metas_app[idx_in_lists]
doc_main_id = doc_meta['id']
if doc_main_id in seen_doc_main_ids: continue # Εμφάνιση μόνο του πιο σχετικού chunk ανά κύριο έγγραφο
original_url_from_meta = doc_meta.get('url', '#')
pdf_gcs_url = "#"
pdf_filename_display = "N/A"
if original_url_from_meta and original_url_from_meta != '#':
pdf_filename_extracted = os.path.basename(original_url_from_meta)
if pdf_filename_extracted and pdf_filename_extracted.lower().endswith(".pdf"):
pdf_gcs_url = f"{GCS_PUBLIC_URL_PREFIX}{pdf_filename_extracted}"
pdf_filename_display = pdf_filename_extracted
elif pdf_filename_extracted: pdf_filename_display = "Source is not a PDF"
# Χρήση raw_chunks_app για το snippet
hits_output.append({
"score": score_val, "title": doc_meta.get('title', 'N/A'),
"snippet": raw_chunks_app[idx_in_lists][:700] + " ...", # Αυξημένο μήκος snippet
"original_url_meta": original_url_from_meta, "pdf_serve_url": pdf_gcs_url,
"pdf_filename_display": pdf_filename_display
})
seen_doc_main_ids.add(doc_main_id)
if len(hits_output) >= k: break
if not hits_output: return "Δεν βρέθηκαν σχετικά αποτελέσματα."
output_md = f"Βρέθηκαν **{len(hits_output)}** σχετικά αποτελέσματα (με χρήση Meltemi-7B):\n\n"
for hit in hits_output:
output_md += f"### {hit['title']} (Score: {hit['score']:.3f})\n"
snippet_wrapped = textwrap.fill(hit['snippet'].replace("\n", " "), width=100)
output_md += f"**Απόσπασμα:** {snippet_wrapped}\n"
if hit['pdf_serve_url'] and hit['pdf_serve_url'] != '#':
output_md += f"**Πηγή (PDF):** <a href='{hit['pdf_serve_url']}' target='_blank'>{hit['pdf_filename_display']}</a>\n"
elif hit['original_url_meta'] and hit['original_url_meta'] != '#':
output_md += f"**Πηγή (αρχικό από metadata):** [{hit['original_url_meta']}]({hit['original_url_meta']})\n"
output_md += "---\n"
return output_md
# ---------------------- GRADIO INTERFACE -----------------------------------
print("🚀 Launching Gradio Interface for Meltemi")
# Ενημέρωση τίτλων και περιγραφών για το ChatbotVol108 και το Meltemi
iface = gr.Interface(
fn=hybrid_search_gradio,
inputs=gr.Textbox(lines=3, placeholder="Γράψε την ερώτησή σου εδώ...", label=f"Ερώτηση προς τον βοηθό (Μοντέλο: {MODEL_NAME.split('/')[-1]}):"),
outputs=gr.Markdown(label="Απαντήσεις από τα έγγραφα:", rtl=False, sanitize_html=False), # sanitize_html=False επιτρέπει τα <a href> links
title=f"🏛️ Ελληνικό Chatbot Υβριδικής Αναζήτησης (Meltemi - {MODEL_NAME.split('/')[-1]})",
description=(f"Πληκτρολογήστε την ερώτησή σας για αναζήτηση. Χρησιμοποιεί το μοντέλο: {MODEL_NAME}.\n"
"Τα PDF ανοίγουν από Google Cloud Storage σε νέα καρτέλα."),
allow_flagging="never",
examples=[ # Μπορείτε να προσαρμόσετε τα παραδείγματα
["Τεχνολογίας τροφίμων;", 5],
["Αμπελουργίας και οινολογίας", 3],
["Ποιες θέσεις αφορούν διδάσκοντες στο Τμήμα Νοσηλευτικής;", 5]
],
)
if __name__ == '__main__':
if not setup_successful:
print("ERROR: Setup was not successful. The Gradio application might not work as expected.")
# Θα μπορούσατε να εμφανίσετε ένα μήνυμα σφάλματος και στο Gradio interface αν το setup απέτυχε
# ή να μην κάνετε launch την εφαρμογή. Για τώρα, απλά τυπώνει στο console.
iface.launch() |