Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
@@ -17,6 +17,7 @@ import torch
|
|
17 |
import faiss
|
18 |
import numpy as np
|
19 |
import gradio as gr
|
|
|
20 |
# from google.colab import drive
|
21 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
22 |
from sentence_transformers import SentenceTransformer
|
@@ -39,7 +40,10 @@ whisper_model = whisper.load_model("base")
|
|
39 |
|
40 |
load_dotenv()
|
41 |
|
|
|
|
|
42 |
hf_token = os.getenv("HF_TOKEN")
|
|
|
43 |
login(token=hf_token)
|
44 |
|
45 |
|
@@ -50,7 +54,7 @@ login(token=hf_token)
|
|
50 |
# π§ Configuration
|
51 |
# -------------------------------
|
52 |
base_model_path = "google/gemma-2-9b-it"
|
53 |
-
peft_model_path = "Jaamie/gemma-mental-health-qlora"
|
54 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
55 |
|
56 |
embedding_model_bge = "BAAI/bge-base-en-v1.5"
|
@@ -205,6 +209,30 @@ def extract_diagnosis(response_text: str) -> str:
|
|
205 |
return line.split(":")[-1].strip()
|
206 |
return "Unknown"
|
207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
def process_query(user_query, input_type="text"):
|
209 |
# Embed the query
|
210 |
query_embedding = embedding_model.encode(user_query, normalize_embeddings=True)
|
@@ -223,6 +251,7 @@ def process_query(user_query, input_type="text"):
|
|
223 |
print(f"Detected emotion: {emotion_result}")
|
224 |
emotion = emotion_result['label']
|
225 |
value = emotion_result['score']
|
|
|
226 |
# Define RAG prompt
|
227 |
prompt_in_chat_format = [
|
228 |
{"role": "user", "content": f"""
|
@@ -268,17 +297,24 @@ def process_query(user_query, input_type="text"):
|
|
268 |
print("β Error during generation:", e)
|
269 |
answer = "β οΈ An error occurred while generating the response."
|
270 |
|
271 |
-
#
|
272 |
-
|
273 |
-
|
274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
275 |
|
276 |
# Extracting diagnosis
|
277 |
diagnosis = extract_diagnosis(answer)
|
278 |
status = "fallback" if diagnosis.lower() == "unknown" else "success"
|
279 |
|
280 |
# Log interaction
|
281 |
-
log_query(input_type=input_type, query=user_query, diagnosis=diagnosis, confidence_score=
|
282 |
download_path = create_summary_txt(answer)
|
283 |
|
284 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
@@ -371,27 +407,27 @@ def show_logs():
|
|
371 |
return f"β οΈ Error: {e}"
|
372 |
|
373 |
|
374 |
-
def create_summary_pdf(text, filename_prefix="diagnosis_report"):
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
|
396 |
|
397 |
|
@@ -491,22 +527,12 @@ def unified_handler(audio, text):
|
|
491 |
else:
|
492 |
response, _ = process_query(text, input_type="text")
|
493 |
|
494 |
-
download_path = create_summary_txt(response)
|
495 |
|
496 |
return response, download_path
|
497 |
|
498 |
-
#Agentic Framework from HF spaces
|
499 |
-
# agent_iframe = gr.HTML(
|
500 |
-
# '<iframe src="https://jaamie-mental-health-agent.hf.space" width="100%" height="700px" style="border:none;"></iframe>'
|
501 |
-
# )
|
502 |
|
503 |
|
504 |
-
# if email:
|
505 |
-
# send_status = send_email_report(to_email=email, response=response)
|
506 |
-
# response += f"\n\n{send_status}"
|
507 |
-
|
508 |
-
# return response, download_path
|
509 |
-
|
510 |
|
511 |
# Gradio UI
|
512 |
|
@@ -540,23 +566,6 @@ logs_tab = gr.Interface(
|
|
540 |
)
|
541 |
|
542 |
|
543 |
-
# π Anonymous Feedback
|
544 |
-
# feedback_tab = gr.Interface(
|
545 |
-
# fn=lambda fb, inp_type, query, diag, score, status: submit_feedback(fb, inp_type, query, diag, score, status),
|
546 |
-
# inputs=[
|
547 |
-
# gr.Textbox(label="π Feedback"),
|
548 |
-
# gr.Textbox(label="Input Type"),
|
549 |
-
# gr.Textbox(label="Query"),
|
550 |
-
# gr.Textbox(label="Diagnosis"),
|
551 |
-
# gr.Textbox(label="Confidence Score"),
|
552 |
-
# gr.Textbox(label="Status")
|
553 |
-
# ],
|
554 |
-
# outputs="text",
|
555 |
-
# title="π Submit Feedback With Session Metadata"
|
556 |
-
# )
|
557 |
-
|
558 |
-
# def feedback_handler(fb, inp_type, query, diag, score, status):
|
559 |
-
# return submit_feedback(fb, inp_type, query, diag, score, status)
|
560 |
|
561 |
feedback_tab = gr.Interface(
|
562 |
fn=submit_feedback,
|
|
|
17 |
import faiss
|
18 |
import numpy as np
|
19 |
import gradio as gr
|
20 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
21 |
# from google.colab import drive
|
22 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
23 |
from sentence_transformers import SentenceTransformer
|
|
|
40 |
|
41 |
load_dotenv()
|
42 |
|
43 |
+
|
44 |
+
|
45 |
hf_token = os.getenv("HF_TOKEN")
|
46 |
+
|
47 |
login(token=hf_token)
|
48 |
|
49 |
|
|
|
54 |
# π§ Configuration
|
55 |
# -------------------------------
|
56 |
base_model_path = "google/gemma-2-9b-it"
|
57 |
+
#peft_model_path = "Jaamie/gemma-mental-health-qlora"
|
58 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
59 |
|
60 |
embedding_model_bge = "BAAI/bge-base-en-v1.5"
|
|
|
209 |
return line.split(":")[-1].strip()
|
210 |
return "Unknown"
|
211 |
|
212 |
+
# calculating the correctness of the answer - Hallucination
|
213 |
+
def calculate_rag_confidence(query_embedding, top_k_docs_embeddings, generation_logprobs=None):
|
214 |
+
"""
|
215 |
+
Combines retriever and generation signals to compute a confidence score.
|
216 |
+
Args:
|
217 |
+
query_embedding (np.ndarray): Embedding vector of the user query (shape: [1, dim]).
|
218 |
+
top_k_docs_embeddings (np.ndarray): Embedding matrix of top-k retrieved documents (shape: [k, dim]).
|
219 |
+
generation_logprobs (list, optional): List of logprobs for generated tokens.
|
220 |
+
Returns:
|
221 |
+
float: Final confidence score (0 to 1).
|
222 |
+
"""
|
223 |
+
retriever_similarities = cosine_similarity(query_embedding, top_k_docs_embeddings)
|
224 |
+
retriever_confidence = float(np.max(retriever_similarities))
|
225 |
+
|
226 |
+
if generation_logprobs:
|
227 |
+
gen_confidence = float(np.exp(np.mean(generation_logprobs)))
|
228 |
+
else:
|
229 |
+
gen_confidence = 0.0 # fallback if unavailable
|
230 |
+
|
231 |
+
alpha, beta = 0.6, 0.4
|
232 |
+
final_confidence = alpha * retriever_confidence + beta * gen_confidence
|
233 |
+
return round(final_confidence, 4)
|
234 |
+
|
235 |
+
# Main Process
|
236 |
def process_query(user_query, input_type="text"):
|
237 |
# Embed the query
|
238 |
query_embedding = embedding_model.encode(user_query, normalize_embeddings=True)
|
|
|
251 |
print(f"Detected emotion: {emotion_result}")
|
252 |
emotion = emotion_result['label']
|
253 |
value = emotion_result['score']
|
254 |
+
|
255 |
# Define RAG prompt
|
256 |
prompt_in_chat_format = [
|
257 |
{"role": "user", "content": f"""
|
|
|
297 |
print("β Error during generation:", e)
|
298 |
answer = "β οΈ An error occurred while generating the response."
|
299 |
|
300 |
+
# Get embeddings of retrieved docs
|
301 |
+
retrieved_doc_embeddings = embedding_model.encode(retrieved_docs, normalize_embeddings=True)
|
302 |
+
retrieved_doc_embeddings = np.array(retrieved_doc_embeddings, dtype=np.float32)
|
303 |
+
|
304 |
+
# Calculate RAG-based confidence
|
305 |
+
confidence_score = calculate_rag_confidence(query_embedding, retrieved_doc_embeddings)
|
306 |
+
|
307 |
+
# Add to response
|
308 |
+
answer += f"\n\nπ§ Accuracy & Closeness of the Answer: {confidence_score:.2f}"
|
309 |
+
answer += "\n\n*Derived from semantic similarity and generation certainty."
|
310 |
+
|
311 |
|
312 |
# Extracting diagnosis
|
313 |
diagnosis = extract_diagnosis(answer)
|
314 |
status = "fallback" if diagnosis.lower() == "unknown" else "success"
|
315 |
|
316 |
# Log interaction
|
317 |
+
log_query(input_type=input_type, query=user_query, diagnosis=diagnosis, confidence_score=confidence_score, status=status)
|
318 |
download_path = create_summary_txt(answer)
|
319 |
|
320 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
407 |
return f"β οΈ Error: {e}"
|
408 |
|
409 |
|
410 |
+
# def create_summary_pdf(text, filename_prefix="diagnosis_report"):
|
411 |
+
# try:
|
412 |
+
# filename = f"{filename_prefix}_{uuid.uuid4().hex[:6]}.pdf"
|
413 |
+
# filepath = os.path.join(".", filename) # Save in current directory
|
414 |
+
# pdf = FPDF()
|
415 |
+
# pdf.add_page()
|
416 |
+
# pdf.set_font("Arial", style='B', size=14)
|
417 |
+
# pdf.cell(200, 10, txt="π§ Mental Health Diagnosis Report", ln=True, align='C')
|
418 |
+
# pdf.set_font("Arial", size=12)
|
419 |
+
# pdf.ln(10)
|
420 |
+
|
421 |
+
# wrapped = textwrap.wrap(text, width=90)
|
422 |
+
# for line in wrapped:
|
423 |
+
# pdf.cell(200, 10, txt=line, ln=True)
|
424 |
+
|
425 |
+
# pdf.output(filepath)
|
426 |
+
# print(f"β
PDF created at: {filepath}")
|
427 |
+
# return filepath
|
428 |
+
# except Exception as e:
|
429 |
+
# print(f"β Error creating PDF: {e}")
|
430 |
+
# return None
|
431 |
|
432 |
|
433 |
|
|
|
527 |
else:
|
528 |
response, _ = process_query(text, input_type="text")
|
529 |
|
530 |
+
download_path = create_summary_txt(response)
|
531 |
|
532 |
return response, download_path
|
533 |
|
|
|
|
|
|
|
|
|
534 |
|
535 |
|
|
|
|
|
|
|
|
|
|
|
|
|
536 |
|
537 |
# Gradio UI
|
538 |
|
|
|
566 |
)
|
567 |
|
568 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
569 |
|
570 |
feedback_tab = gr.Interface(
|
571 |
fn=submit_feedback,
|