|
import gradio as gr |
|
import torch |
|
import unicodedata |
|
import re |
|
import numpy as np |
|
from pathlib import Path |
|
from transformers import AutoTokenizer, 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 |
|
import tqdm.auto as tq |
|
|
|
|
|
|
|
MODEL_NAME = "ilsp/Meltemi-7B-Instruct-v1.5" |
|
PERSISTENT_STORAGE_ROOT = Path("/data") |
|
|
|
DB_DIR_APP = PERSISTENT_STORAGE_ROOT / "chroma_db_ChatbotVol108_Meltemi" |
|
COL_NAME = "collection_chatbotvol108_meltemi" |
|
ASSETS_DIR_APP = PERSISTENT_STORAGE_ROOT / "assets_ChatbotVol108_Meltemi" |
|
|
|
|
|
DATA_PATH_FOR_SETUP = "./dataset14.json" |
|
|
|
|
|
GCS_BUCKET_NAME = "chatbotthesisihu" |
|
GCS_PUBLIC_URL_PREFIX = f"https://storage.googleapis.com/{GCS_BUCKET_NAME}/" |
|
|
|
|
|
CHUNK_SIZE = 512 |
|
CHUNK_OVERLAP = 40 |
|
BATCH_EMB = 8 |
|
ALPHA_BASE = 0.2 |
|
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)}") |
|
|
|
|
|
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): |
|
|
|
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): |
|
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] |
|
|
|
|
|
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() |
|
for i in tq.tqdm(range(0, len(texts), bs), desc="Embedding texts for DB setup (Mean Pooling)"): |
|
batch_texts = texts[i:i+bs] |
|
|
|
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'] |
|
|
|
|
|
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...") |
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
tokenizer_setup = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True) |
|
|
|
if tokenizer_setup.pad_token is None: |
|
tokenizer_setup.pad_token = tokenizer_setup.eos_token |
|
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, |
|
|
|
).to(DEVICE).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)) |
|
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"}) |
|
|
|
print("⏳ (Setup) Encoding chunks (using mean pooling) and streaming to ChromaDB...") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
all_embeddings_list = [] |
|
|
|
|
|
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...") |
|
|
|
|
|
db_add_batch_size = 5000 |
|
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] |
|
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, |
|
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() |
|
|
|
|
|
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) |
|
|
|
|
|
def mean_pooling_embed_app(texts, tokenizer_app, model_app, device_app, max_length_embed=CHUNK_SIZE): |
|
|
|
model_app.eval() |
|
|
|
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() |
|
|
|
|
|
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`.") |
|
|
|
|
|
model_app = AutoModel.from_pretrained( |
|
MODEL_NAME, |
|
torch_dtype=torch.float16, |
|
trust_remote_code=True, |
|
|
|
).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. !!!") |
|
|
|
|
|
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: |
|
return "Σφάλμα: Η εφαρμογή δεν αρχικοποιήθηκε σωστά. Τα δεδομένα ή το μοντέλο δεν φορτώθηκαν. Ελέγξτε τα logs εκκίνησης." |
|
if not query.strip(): |
|
return "Παρακαλώ εισάγετε μια ερώτηση." |
|
|
|
q_pre = preprocess(query) |
|
words = q_pre.split() |
|
alpha = ALPHA_LONGQ if len(words) > 30 else ALPHA_BASE |
|
|
|
|
|
|
|
|
|
|
|
q_emb_np = mean_pooling_embed_app([q_pre], tok_app, model_app, DEVICE, max_length_embed=CHUNK_SIZE) |
|
q_emb_list = q_emb_np.tolist() |
|
|
|
try: |
|
|
|
sem_results_count = min(k * 30, len(ids_app)) if ids_app else k * 30 |
|
if sem_results_count <=0: sem_results_count = k |
|
|
|
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])} |
|
|
|
|
|
|
|
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 |
|
else: print(f"Warning (hybrid_search): Lexical score index {idx} out of bounds for ids_app list (len: {len(ids_app)}).") |
|
|
|
|
|
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 |
|
scored.append((chunk_id_key, s)) |
|
|
|
scored.sort(key=lambda x: x[1], reverse=True) |
|
|
|
|
|
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 |
|
|
|
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" |
|
|
|
|
|
hits_output.append({ |
|
"score": score_val, "title": doc_meta.get('title', 'N/A'), |
|
"snippet": raw_chunks_app[idx_in_lists][:700] + " ...", |
|
"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 |
|
|
|
|
|
print("🚀 Launching Gradio Interface for 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), |
|
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.") |
|
|
|
|
|
iface.launch() |