TzepChris commited on
Commit
f3e9575
·
verified ·
1 Parent(s): 2e7464d

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +292 -0
app.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ # --------------------------- CONFIG -----------------------------------
18
+ DB_DIR = Path("./chroma_db_greekbertChatbotVol106")
19
+ ASSETS_DIR = Path("./assets")
20
+ STATIC_PDF_DIR = Path("./static_pdfs")
21
+ STATIC_PDF_DIR_NAME = "static_pdfs"
22
+
23
+ COL_NAME = "dataset14_grbert_charword"
24
+ MODEL_NAME = "sentence-transformers/paraphrase-xlm-r-multilingual-v1"
25
+ CHUNK_SIZE = 512
26
+ ALPHA_BASE = 0.2
27
+ ALPHA_LONGQ = 0.5
28
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
29
+
30
+ print(f"Running on device: {DEVICE}")
31
+
32
+ # ----------------------- PRE-/POST HELPERS ----------------------------
33
+ def strip_acc(s: str) -> str:
34
+ return ''.join(ch for ch in unicodedata.normalize('NFD', s)
35
+ if not unicodedata.combining(ch))
36
+
37
+ STOP = {"σχετικο", "σχετικα", "με", "και"}
38
+
39
+ def preprocess(txt: str) -> str:
40
+ txt = strip_acc(txt.lower())
41
+ txt = re.sub(r"[^a-zα-ω0-9 ]", " ", txt)
42
+ txt = re.sub(r"\s+", " ", txt).strip()
43
+ return " ".join(w for w in txt.split() if w not in STOP)
44
+
45
+ def cls_embed(texts, tok, model):
46
+ out = []
47
+ enc = tok(texts, padding=True, truncation=True,
48
+ max_length=CHUNK_SIZE, return_tensors="pt").to(DEVICE)
49
+ with torch.no_grad():
50
+ hs = model(**enc, output_hidden_states=True).hidden_states
51
+ cls = torch.stack(hs[-4:],0).mean(0)[:,0,:]
52
+ cls = torch.nn.functional.normalize(cls, p=2, dim=1)
53
+ out.append(cls.cpu())
54
+ return torch.cat(out).numpy()
55
+
56
+ # ---------------------- LOAD MODELS & DATA (Μία φορά κατά την εκκίνηση) --------------------
57
+ print("⏳ Loading Model and Tokenizer...")
58
+ try:
59
+ tok = AutoTokenizer.from_pretrained(MODEL_NAME)
60
+ model = AutoModel.from_pretrained(MODEL_NAME).to(DEVICE).eval()
61
+ print("✓ Model and tokenizer loaded.")
62
+ except Exception as e:
63
+ print(f"CRITICAL ERROR loading model/tokenizer: {e}")
64
+ raise
65
+
66
+ print("⏳ Loading TF-IDF vectorizers and SPARSE matrices...")
67
+ try:
68
+ char_vec = joblib.load(ASSETS_DIR / "char_vectorizer.joblib")
69
+ word_vec = joblib.load(ASSETS_DIR / "word_vectorizer.joblib")
70
+ X_char = scipy.sparse.load_npz(ASSETS_DIR / "X_char_sparse.npz")
71
+ X_word = scipy.sparse.load_npz(ASSETS_DIR / "X_word_sparse.npz")
72
+ print("✓ TF-IDF components loaded (sparse matrices).")
73
+ print(f" → X_char shape: {X_char.shape}, type: {type(X_char)}")
74
+ print(f" → X_word shape: {X_word.shape}, type: {type(X_word)}")
75
+ except Exception as e:
76
+ print(f"CRITICAL ERROR loading TF-IDF components: {e}")
77
+ raise
78
+
79
+ print("⏳ Loading chunk data (pre_chunks, raw_chunks, ids, metas)...")
80
+ try:
81
+ with open(ASSETS_DIR / "pre_chunks.pkl", "rb") as f:
82
+ pre_chunks = pickle.load(f)
83
+ with open(ASSETS_DIR / "raw_chunks.pkl", "rb") as f:
84
+ raw_chunks = pickle.load(f)
85
+ with open(ASSETS_DIR / "ids.pkl", "rb") as f:
86
+ ids = pickle.load(f)
87
+ with open(ASSETS_DIR / "metas.pkl", "rb") as f:
88
+ metas = pickle.load(f)
89
+ print(f"✓ Chunk data loaded. Total chunks from ids: {len(ids):,}")
90
+ if not all([pre_chunks, raw_chunks, ids, metas]):
91
+ print("WARNING: One or more chunk data lists are empty!")
92
+ except Exception as e:
93
+ print(f"CRITICAL ERROR loading chunk data: {e}")
94
+ raise
95
+
96
+ print("⏳ Connecting to ChromaDB...")
97
+ try:
98
+ client = chromadb.PersistentClient(path=str(DB_DIR.resolve()))
99
+ col = client.get_collection(COL_NAME)
100
+ print(f"✓ Connected to ChromaDB. Collection '{COL_NAME}' count: {col.count()}")
101
+ if col.count() == 0:
102
+ print("WARNING: ChromaDB collection is empty or not found correctly!")
103
+ except Exception as e:
104
+ print(f"CRITICAL ERROR connecting to ChromaDB or getting collection: {e}")
105
+ print(f"Attempted DB path for PersistentClient: {str(DB_DIR.resolve())}")
106
+ print("Ensure the ChromaDB directory structure is correct in your Hugging Face Space repository.")
107
+ raise
108
+
109
+ # ---------------------- HYBRID SEARCH (Κύρια Λογική) ---------------------------------
110
+ def hybrid_search_gradio(query, k=5):
111
+ if not query.strip():
112
+ return "Παρακαλώ εισάγετε μια ερώτηση."
113
+
114
+ if not ids:
115
+ return "Σφάλμα: Τα δεδομένα αναζήτησης (ids) δεν έχουν φορτωθεί. Επικοινωνήστε με τον διαχειριστή."
116
+
117
+ q_pre = preprocess(query)
118
+ words = q_pre.split()
119
+ alpha = ALPHA_LONGQ if len(words) > 30 else ALPHA_BASE
120
+
121
+ exact_ids_set = {ids[i] for i, t in enumerate(pre_chunks) if q_pre in t}
122
+
123
+ q_emb_np = cls_embed([q_pre], tok, model)
124
+ q_emb_list = q_emb_np.tolist()
125
+
126
+ try:
127
+ sem_results = col.query(
128
+ query_embeddings=q_emb_list,
129
+ n_results=min(k * 30, len(ids)),
130
+ include=["distances", "metadatas", "documents"]
131
+ )
132
+ except Exception as e:
133
+ print(f"ERROR during ChromaDB query: {e}")
134
+ return "Σφάλμα κατά την σημασιολογική αναζήτηση."
135
+
136
+ sem_sims = {doc_id: 1 - dist for doc_id, dist in zip(sem_results["ids"][0], sem_results["distances"][0])}
137
+
138
+ q_char_sparse = char_vec.transform([q_pre])
139
+ q_char_normalized = sk_normalize(q_char_sparse)
140
+ char_sim_scores = (q_char_normalized @ X_char.T).toarray().flatten()
141
+
142
+ q_word_sparse = word_vec.transform([q_pre])
143
+ q_word_normalized = sk_normalize(q_word_sparse)
144
+ word_sim_scores = (q_word_normalized @ X_word.T).toarray().flatten()
145
+
146
+ lex_sims = {}
147
+ for idx, (c_score, w_score) in enumerate(zip(char_sim_scores, word_sim_scores)):
148
+ if c_score > 0 or w_score > 0:
149
+ if idx < len(ids):
150
+ lex_sims[ids[idx]] = 0.85 * c_score + 0.15 * w_score
151
+ else:
152
+ print(f"Warning: Lexical score index {idx} out of bounds for ids list (len: {len(ids)}).")
153
+
154
+ all_chunk_ids_set = set(sem_sims.keys()) | set(lex_sims.keys()) | exact_ids_set
155
+ scored = []
156
+ for chunk_id_key in all_chunk_ids_set:
157
+ s = alpha * sem_sims.get(chunk_id_key, 0.0) + \
158
+ (1 - alpha) * lex_sims.get(chunk_id_key, 0.0)
159
+ if chunk_id_key in exact_ids_set:
160
+ s = 1.0
161
+ scored.append((chunk_id_key, s))
162
+
163
+ scored.sort(key=lambda x: x[1], reverse=True)
164
+
165
+ hits_output = []
166
+ seen_doc_main_ids = set()
167
+ for chunk_id_val, score_val in scored:
168
+ try:
169
+ idx_in_lists = ids.index(chunk_id_val)
170
+ except ValueError:
171
+ print(f"Warning: chunk_id '{chunk_id_val}' from search results not found in global 'ids' list. Skipping.")
172
+ continue
173
+
174
+ doc_meta = metas[idx_in_lists]
175
+ doc_main_id = doc_meta['id']
176
+
177
+ if doc_main_id in seen_doc_main_ids:
178
+ continue
179
+
180
+ original_url_from_meta = doc_meta.get('url', '#')
181
+
182
+ # *** ΕΝΑΡΞΗ ΤΡΟΠΟΠΟΙΗΜΕΝΟΥ/ΝΕΟΥ ΚΩΔΙΚΑ ΓΙΑ PDF DEBUGGING ***
183
+ pdf_serve_url = "#"
184
+ pdf_filename_display = "N/A"
185
+ pdf_filename_extracted = None # Αρχικοποίηση
186
+
187
+ if original_url_from_meta and original_url_from_meta != '#':
188
+ pdf_filename_extracted = os.path.basename(original_url_from_meta)
189
+ print(f"--- Debug: Original URL: {original_url_from_meta}, Initial Extracted filename: {pdf_filename_extracted}")
190
+
191
+ # --- ΠΡΟΣΩΡΙΝΟΣ ΚΩΔΙΚΑΣ ΓΙΑ ΔΟΚΙΜΗ ASCII FILENAME (Μπορείτε να τον ενεργοποιήσετε αφαιρώντας τα σχόλια) ---
192
+ # TARGET_ORIGINAL_FILENAME_FOR_TEST = "6ΑΤΘ469Β7Η-963.pdf" # Το αρχικό ελληνικό όνομα που είχατε μετονομάσει
193
+ # ASCII_TEST_FILENAME = "testfileGR.pdf" # Το νέο ASCII όνομα που βάλατε στο static_pdfs
194
+ #
195
+ # if pdf_filename_extracted == TARGET_ORIGINAL_FILENAME_FOR_TEST:
196
+ # print(f"--- INFO: ASCII Filename Test Active ---")
197
+ # print(f"--- Original filename was: {pdf_filename_extracted}")
198
+ # print(f"--- Temporarily using: {ASCII_TEST_FILENAME} for linking and checking existence.")
199
+ # pdf_filename_extracted = ASCII_TEST_FILENAME
200
+ # --- ΤΕΛΟΣ ΠΡΟΣΩΡΙΝΟΥ ΚΩΔΙΚΑ ASCII ---
201
+
202
+ if pdf_filename_extracted and pdf_filename_extracted.lower().endswith(".pdf"):
203
+ potential_pdf_path_on_server = STATIC_PDF_DIR / pdf_filename_extracted
204
+
205
+ print(f"--- Debug: Final pdf_filename_extracted to check: {pdf_filename_extracted}")
206
+ print(f"--- Debug: Checking for PDF at server path: {potential_pdf_path_on_server.resolve()}")
207
+
208
+ if potential_pdf_path_on_server.exists() and potential_pdf_path_on_server.is_file():
209
+ print(f"--- Debug: Path.exists() and Path.is_file() are TRUE for {potential_pdf_path_on_server.resolve()}. Attempting to open...")
210
+ try:
211
+ # Προσπάθεια ανοίγματος του αρχείου σε binary read mode και ανάγνωσης ενός byte
212
+ with open(potential_pdf_path_on_server, "rb") as f_test_access:
213
+ f_test_access.read(1)
214
+ print(f"--- Debug: Successfully opened and read a byte from: {potential_pdf_path_on_server.resolve()}")
215
+
216
+ pdf_serve_url = f"/file/{STATIC_PDF_DIR_NAME}/{pdf_filename_extracted}"
217
+ pdf_filename_display = pdf_filename_extracted
218
+
219
+ except Exception as e_file_access:
220
+ print(f"!!! CRITICAL ERROR trying to open/read file {potential_pdf_path_on_server.resolve()}: {e_file_access}")
221
+ pdf_filename_display = "Error accessing file content" # Ενημέρωση για εμφάνιση
222
+ else:
223
+ print(f"--- Debug: Path.exists() or Path.is_file() is FALSE for {potential_pdf_path_on_server.resolve()}")
224
+ pdf_filename_display = "File not found by script"
225
+ else:
226
+ if not pdf_filename_extracted: # Αν το pdf_filename_extracted κατέληξε κενό
227
+ print(f"--- Debug: pdf_filename_extracted is empty or None after os.path.basename or ASCII test.")
228
+ else: # Αν δεν έχει επέκταση .pdf
229
+ print(f"--- Debug: Extracted filename '{pdf_filename_extracted}' does not end with .pdf")
230
+ pdf_filename_display = "Not a valid PDF link"
231
+ else: # original_url_from_meta ήταν κενό ή '#'
232
+ print(f"--- Debug: No valid original_url_from_meta found. URL was: '{original_url_from_meta}'")
233
+ pdf_filename_display = "No source URL"
234
+
235
+ # *** ΤΕΛΟΣ ΤΡΟΠΟΠΟΙΗΜΕΝΟΥ/ΝΕΟΥ ΚΩΔΙΚΑ ΓΙΑ PDF DEBUGGING ***
236
+
237
+ hits_output.append({
238
+ "score": score_val,
239
+ "title": doc_meta.get('title', 'N/A'),
240
+ "snippet": raw_chunks[idx_in_lists][:500] + " ...",
241
+ "original_url_meta": original_url_from_meta,
242
+ "pdf_serve_url": pdf_serve_url,
243
+ "pdf_filename_display": pdf_filename_display
244
+ })
245
+ seen_doc_main_ids.add(doc_main_id)
246
+ if len(hits_output) >= k:
247
+ break
248
+
249
+ if not hits_output:
250
+ return "Δεν βρέθηκαν σχετικά αποτελέσματα."
251
+
252
+ output_md = f"Βρέθηκαν **{len(hits_output)}** σχετικά αποτελέσματα:\n\n"
253
+ for hit in hits_output:
254
+ output_md += f"### {hit['title']} (Score: {hit['score']:.3f})\n"
255
+ snippet_wrapped = textwrap.fill(hit['snippet'].replace("\n", " "), width=100)
256
+ output_md += f"**Απόσπασμα:** {snippet_wrapped}\n"
257
+
258
+ if hit['pdf_serve_url'] and hit['pdf_serve_url'] != '#':
259
+ output_md += f"**Πηγή (PDF):** <a href='{hit['pdf_serve_url']}' target='_blank'>{hit['pdf_filename_display']}</a>\n"
260
+ elif hit['original_url_meta'] and hit['original_url_meta'] != '#':
261
+ output_md += f"**Πηγή (αρχικό):** [{hit['original_url_meta']}]({hit['original_url_meta']})\n"
262
+ output_md += "---\n"
263
+
264
+ # ΠΡΟΣΩΡΙΝΗ ΠΡΟΣΘΗΚΗ ΓΙΑ ΔΟΚΙΜΗ TXT ΑΡΧΕΙΟΥ
265
+ # Βεβαιωθείτε ότι έχετε ανεβάσει το 'test_text_file.txt' στον φάκελο 'static_pdfs'.
266
+ # Αυτός ο σύνδεσμος θα εμφανιστεί στο κάτω μέρος των αποτελεσμάτων αναζήτησης.
267
+ output_md += "\n\n---\n**Δοκιμαστικός Σύνδεσμος Κειμένου:** <a href='/file/static_pdfs/test_text_file.txt' target='_blank'>Άνοιγμα test_text_file.txt</a>\n"
268
+ # Η ρύθμιση sanitize_html=False στο gr.Markdown που έχετε ήδη, επιτρέπει αυτή την HTML.
269
+
270
+ return output_md
271
+
272
+
273
+ # ---------------------- GRADIO INTERFACE -----------------------------------
274
+ print("🚀 Launching Gradio Interface...")
275
+ iface = gr.Interface(
276
+ fn=hybrid_search_gradio,
277
+ inputs=gr.Textbox(lines=3, placeholder="Γράψε την ερώτησή σου εδώ...", label="Ερώτηση προς τον βοηθό:"),
278
+ outputs=gr.Markdown(label="Απαντήσεις από τα έγγραφα:", rtl=False, sanitize_html=False),
279
+ title="🏛️ Ελληνικό Chatbot Υβριδικής Αναζήτησης (v1.0.9)", # Νέα έκδοση για παρακολούθηση
280
+ description="Πληκτρολογήστε την ερώτησή σας για αναζήτηση στα διαθέσιμα έγγραφα. Η αναζήτηση συνδυάζει σημασιολογική ομοιότητα (GreekBERT) και ομοιότητα λέξεων/χαρακτήρων (TF-IDF).\nΧρησιμοποιεί το μοντέλο: sentence-transformers/paraphrase-xlm-r-multilingual-v1.\nΤα PDF ανοίγουν σε νέα καρτέλα.",
281
+ allow_flagging="never",
282
+ examples=[
283
+ ["Ποια είναι τα μέτρα για τον κορονοϊό;", 5],
284
+ ["Πληροφορίες για άδεια ειδικού σκοπού", 3],
285
+ ["Τι προβλέπεται για τις μετακινήσεις εκτός νομού;", 5]
286
+ ],
287
+ )
288
+
289
+ if __name__ == '__main__':
290
+ # Παραλλαγή 2
291
+ # STATIC_PDF_DIR ορίζεται στην αρχή του αρχείου ως Path("./static_pdfs")
292
+ iface.launch(allowed_paths=[str(STATIC_PDF_DIR.resolve())])