Delete model.py
Browse files
model.py
DELETED
|
@@ -1,130 +0,0 @@
|
|
| 1 |
-
import chromadb
|
| 2 |
-
import traceback
|
| 3 |
-
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
| 4 |
-
from retriever import retrieve
|
| 5 |
-
from utils import build_prompt, refine_response
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
# ============================================================================
|
| 9 |
-
# LOAD MODELS AND VECTOR STORE ONCE AT STARTUP
|
| 10 |
-
# ============================================================================
|
| 11 |
-
|
| 12 |
-
# Load vector store
|
| 13 |
-
db_client = chromadb.PersistentClient(path="./MedQuAD_db")
|
| 14 |
-
try:
|
| 15 |
-
vector_store = db_client.get_collection("medical_rag")
|
| 16 |
-
except:
|
| 17 |
-
# If collection doesn't exist, create it
|
| 18 |
-
vector_store = db_client.create_collection(name="medical_rag")
|
| 19 |
-
|
| 20 |
-
# Load fine-tuned model for generation
|
| 21 |
-
ft_model_id = "amiraghhh/fine-tuned-flan-t5-small"
|
| 22 |
-
ft_tokenizer = AutoTokenizer.from_pretrained(ft_model_id)
|
| 23 |
-
ft_model = AutoModelForSeq2SeqLM.from_pretrained(ft_model_id)
|
| 24 |
-
|
| 25 |
-
finetuned_llm = pipeline(
|
| 26 |
-
"text2text-generation",
|
| 27 |
-
model=ft_model,
|
| 28 |
-
tokenizer=ft_tokenizer,
|
| 29 |
-
decoder_start_token_id=ft_model.config.pad_token_id
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
# Load base model config for EOS token
|
| 33 |
-
base_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small")
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
# ============================================================================
|
| 37 |
-
# MAIN RAG FUNCTION
|
| 38 |
-
# ============================================================================
|
| 39 |
-
|
| 40 |
-
def rag(user_query):
|
| 41 |
-
"""Main RAG function: retrieve context and generate answer.
|
| 42 |
-
Takes a question string and returns an answer string with confidence.
|
| 43 |
-
Returns: str(generated_answer)"""
|
| 44 |
-
|
| 45 |
-
try:
|
| 46 |
-
# 1. Check for emergency keywords
|
| 47 |
-
emergency_keywords = ["emergency", "severe pain", "bleeding",
|
| 48 |
-
"blind", "lose consciousness", "pass out"]
|
| 49 |
-
|
| 50 |
-
if any(keyword in user_query.lower() for keyword in emergency_keywords):
|
| 51 |
-
emergency_msg = """I am an AI and cannot provide medical advice for emergencies.
|
| 52 |
-
PLEASE contact emergency services or a medical professional immediately."""
|
| 53 |
-
|
| 54 |
-
try:
|
| 55 |
-
# Still generate answer for context
|
| 56 |
-
contexts = retrieve(vector_store, user_query, top_k=3, use_reranking=True)
|
| 57 |
-
|
| 58 |
-
if not contexts:
|
| 59 |
-
return f"{emergency_msg}\n\nNo relevant information found for your query."
|
| 60 |
-
|
| 61 |
-
prompt = build_prompt(user_query, contexts)
|
| 62 |
-
result = finetuned_llm(
|
| 63 |
-
prompt,
|
| 64 |
-
max_new_tokens=70,
|
| 65 |
-
num_beams=3,
|
| 66 |
-
early_stopping=True,
|
| 67 |
-
do_sample=False,
|
| 68 |
-
repetition_penalty=1.4,
|
| 69 |
-
eos_token_id=finetuned_llm.tokenizer.eos_token_id
|
| 70 |
-
)
|
| 71 |
-
|
| 72 |
-
answer = result[0]['generated_text'].strip()
|
| 73 |
-
answer = refine_response(answer)
|
| 74 |
-
|
| 75 |
-
# Calculate confidence
|
| 76 |
-
if contexts:
|
| 77 |
-
avg_distance = sum(c.get('chroma_distance', 1.0) for c in contexts) / len(contexts)
|
| 78 |
-
confidence_score = (1 - avg_distance) * 100
|
| 79 |
-
confidence_score = max(0, min(100, confidence_score))
|
| 80 |
-
else:
|
| 81 |
-
confidence_score = 0
|
| 82 |
-
|
| 83 |
-
return f"{emergency_msg}\n\n[Confidence: {confidence_score:.1f}%]\n\n{answer}"
|
| 84 |
-
|
| 85 |
-
except Exception as e:
|
| 86 |
-
return f"{emergency_msg}\n\nError generating answer: {str(e)}"
|
| 87 |
-
|
| 88 |
-
# 2. Retrieve relevant contexts
|
| 89 |
-
contexts = retrieve(vector_store, user_query, top_k=3, use_reranking=True)
|
| 90 |
-
|
| 91 |
-
if not contexts:
|
| 92 |
-
return "I'm not confident about my answer (0%).\n\nCouldn't find relevant information to answer your question."
|
| 93 |
-
|
| 94 |
-
# 3. Build prompt with context
|
| 95 |
-
prompt = build_prompt(user_query, contexts)
|
| 96 |
-
|
| 97 |
-
# 4. Generate answer
|
| 98 |
-
result = finetuned_llm(
|
| 99 |
-
prompt,
|
| 100 |
-
max_new_tokens=70,
|
| 101 |
-
num_beams=3,
|
| 102 |
-
early_stopping=True,
|
| 103 |
-
do_sample=False,
|
| 104 |
-
repetition_penalty=1.4,
|
| 105 |
-
eos_token_id=finetuned_llm.tokenizer.eos_token_id
|
| 106 |
-
)
|
| 107 |
-
|
| 108 |
-
answer = result[0]['generated_text'].strip()
|
| 109 |
-
answer = refine_response(answer)
|
| 110 |
-
|
| 111 |
-
# 5. Calculate confidence score based on retrieval quality
|
| 112 |
-
if contexts and len(contexts) > 0:
|
| 113 |
-
avg_distance = sum(c.get('chroma_distance', 1.0) for c in contexts) / len(contexts)
|
| 114 |
-
confidence_score = (1 - avg_distance) * 100
|
| 115 |
-
confidence_score = max(0, min(100, confidence_score))
|
| 116 |
-
|
| 117 |
-
# Build final response with confidence
|
| 118 |
-
if confidence_score < 40:
|
| 119 |
-
final_response = f"I'm not confident about my answer ({confidence_score:.1f}%).\n\n{answer}"
|
| 120 |
-
else:
|
| 121 |
-
final_response = f"{answer}\n\n[Confidence: {confidence_score:.1f}%]"
|
| 122 |
-
else:
|
| 123 |
-
final_response = "I'm not confident about my answer (0%).\n\n" + answer
|
| 124 |
-
|
| 125 |
-
return final_response
|
| 126 |
-
|
| 127 |
-
except Exception as e:
|
| 128 |
-
error_msg = f"ERROR in RAG pipeline: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 129 |
-
print(error_msg)
|
| 130 |
-
return error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|