Spaces:
Build error
Build error
Commit ·
9f5c02d
1
Parent(s): 4a9b71d
initial commit
Browse files- .gitignore +1 -0
- app.py +21 -0
- chatbot.py +132 -0
- requirements.txt +8 -0
- static/logo.png +0 -0
- templates/index.html +173 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.env
|
app.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify, render_template
|
| 2 |
+
import chatbot # Import your chatbot logic from chatbot.py
|
| 3 |
+
import streamlit as st
|
| 4 |
+
|
| 5 |
+
app = Flask(__name__)
|
| 6 |
+
|
| 7 |
+
@app.route("/")
|
| 8 |
+
def index():
|
| 9 |
+
return render_template("index.html")
|
| 10 |
+
|
| 11 |
+
@app.route("/ask", methods=["POST"])
|
| 12 |
+
def ask():
|
| 13 |
+
data = request.get_json()
|
| 14 |
+
question = data.get("question")
|
| 15 |
+
if not question:
|
| 16 |
+
return jsonify({"answer": "No question provided."})
|
| 17 |
+
answer = chatbot.chatbot_response(question)
|
| 18 |
+
return jsonify({"answer": answer})
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
app.run(host="0.0.0.0", port=8080, debug=True)
|
chatbot.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, re, os, pickle, numpy as np
|
| 2 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 3 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoTokenizer as GenAutoTokenizer
|
| 5 |
+
import openai
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
# Use the environment variable for the API key
|
| 12 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 13 |
+
|
| 14 |
+
####################################
|
| 15 |
+
# 1. Load and Clean JSON Data
|
| 16 |
+
####################################
|
| 17 |
+
DATA_PATH = "dbcontent.txt"
|
| 18 |
+
with open(DATA_PATH, "r") as f:
|
| 19 |
+
raw = f.read()
|
| 20 |
+
cleaned = re.sub(r'ObjectId\("([^"]+)"\)', r'"\1"', raw)
|
| 21 |
+
data = json.loads(cleaned)
|
| 22 |
+
documents = [
|
| 23 |
+
{
|
| 24 |
+
"transcript": doc["transcribetext"],
|
| 25 |
+
"coursename": doc.get("coursename", "Unknown Course"),
|
| 26 |
+
"videoname": doc.get("videoname", "Unknown Video"),
|
| 27 |
+
"videourl": doc.get("videourl", "No URL")
|
| 28 |
+
}
|
| 29 |
+
for doc in data if "transcribetext" in doc
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
####################################
|
| 33 |
+
# 2. Chunking the Documents
|
| 34 |
+
####################################
|
| 35 |
+
def chunk_text(text, tokenizer, max_tokens=512):
|
| 36 |
+
tokens = tokenizer.encode(text)
|
| 37 |
+
return [
|
| 38 |
+
tokenizer.decode(tokens[i:i+max_tokens], skip_special_tokens=True)
|
| 39 |
+
for i in range(0, len(tokens), max_tokens)
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
sbert_tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
| 43 |
+
all_chunks = []
|
| 44 |
+
for doc in documents:
|
| 45 |
+
for chunk in chunk_text(doc["transcript"], sbert_tokenizer, max_tokens=512):
|
| 46 |
+
all_chunks.append({
|
| 47 |
+
"chunk": chunk,
|
| 48 |
+
"coursename": doc["coursename"],
|
| 49 |
+
"videoname": doc["videoname"],
|
| 50 |
+
"videourl": doc["videourl"]
|
| 51 |
+
})
|
| 52 |
+
|
| 53 |
+
####################################
|
| 54 |
+
# 3. Build a TF-IDF Index for Fast Retrieval with Caching
|
| 55 |
+
####################################
|
| 56 |
+
chunk_texts = [item["chunk"] for item in all_chunks]
|
| 57 |
+
vectorizer_cache = "vectorizer.pkl"
|
| 58 |
+
tfidf_cache = "tfidf_matrix.pkl"
|
| 59 |
+
|
| 60 |
+
if os.path.exists(vectorizer_cache) and os.path.exists(tfidf_cache):
|
| 61 |
+
with open(vectorizer_cache, "rb") as f:
|
| 62 |
+
vectorizer = pickle.load(f)
|
| 63 |
+
with open(tfidf_cache, "rb") as f:
|
| 64 |
+
tfidf_matrix = pickle.load(f)
|
| 65 |
+
else:
|
| 66 |
+
vectorizer = TfidfVectorizer(stop_words='english')
|
| 67 |
+
tfidf_matrix = vectorizer.fit_transform(chunk_texts)
|
| 68 |
+
with open(vectorizer_cache, "wb") as f:
|
| 69 |
+
pickle.dump(vectorizer, f)
|
| 70 |
+
with open(tfidf_cache, "wb") as f:
|
| 71 |
+
pickle.dump(tfidf_matrix, f)
|
| 72 |
+
|
| 73 |
+
def get_relevant_chunk(query):
|
| 74 |
+
query_vec = vectorizer.transform([query])
|
| 75 |
+
cosine_sim = cosine_similarity(query_vec, tfidf_matrix)
|
| 76 |
+
idx = np.argmax(cosine_sim)
|
| 77 |
+
return all_chunks[idx]
|
| 78 |
+
|
| 79 |
+
####################################
|
| 80 |
+
# 4. Set Up Generation Model (DialoGPT-medium)
|
| 81 |
+
####################################
|
| 82 |
+
gen_tokenizer = GenAutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
| 83 |
+
gen_model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
|
| 84 |
+
def generate_answer(prompt):
|
| 85 |
+
inputs = gen_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
|
| 86 |
+
outputs = gen_model.generate(inputs["input_ids"], max_new_tokens=100, pad_token_id=gen_tokenizer.eos_token_id)
|
| 87 |
+
return gen_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 88 |
+
|
| 89 |
+
####################################
|
| 90 |
+
# 5. Refine the Answer Using GPT-3.5-turbo (ChatGPT)
|
| 91 |
+
####################################
|
| 92 |
+
def refine_answer(initial_answer, query, sources_text):
|
| 93 |
+
refinement_prompt = (
|
| 94 |
+
"You are an expert editor. Rewrite the answer below so that it is clear, grammatically correct, "
|
| 95 |
+
"and directly addresses the question in under 100 words. Do not include citation information, "
|
| 96 |
+
"course name, video name, or URL. Use only the provided information and do not include external data.\n\n"
|
| 97 |
+
f"Question: {query}\n\n"
|
| 98 |
+
f"Initial Answer: {initial_answer}\n\n"
|
| 99 |
+
f"Sources: {sources_text}\n\n"
|
| 100 |
+
"Refined Answer:"
|
| 101 |
+
)
|
| 102 |
+
response = openai.ChatCompletion.create(
|
| 103 |
+
model="gpt-3.5-turbo",
|
| 104 |
+
messages=[
|
| 105 |
+
{"role": "system", "content": "You are a skilled editor."},
|
| 106 |
+
{"role": "user", "content": refinement_prompt}
|
| 107 |
+
],
|
| 108 |
+
temperature=0.7,
|
| 109 |
+
max_tokens=150
|
| 110 |
+
)
|
| 111 |
+
return response.choices[0].message["content"]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
####################################
|
| 115 |
+
# 6. Chatbot Response with Citation and Refinement
|
| 116 |
+
####################################
|
| 117 |
+
def chatbot_response(query):
|
| 118 |
+
relevant = get_relevant_chunk(query)
|
| 119 |
+
context = relevant["chunk"]
|
| 120 |
+
# Format the sources as HTML anchor tag to ensure they display fully
|
| 121 |
+
sources_text = f"Course: {relevant['coursename']}, Video: <a href='{relevant['videourl']}' target='_blank'>{relevant['videoname']}</a>"
|
| 122 |
+
prompt = (
|
| 123 |
+
"Using only the context below, generate a concise, direct answer in under 100 words that addresses the question. "
|
| 124 |
+
"Summarize and rephrase the relevant information in your own words.\n\n"
|
| 125 |
+
f"Context:\n{context}\n\n"
|
| 126 |
+
f"Question: {query}\n\n"
|
| 127 |
+
"Answer:"
|
| 128 |
+
)
|
| 129 |
+
initial_answer = generate_answer(prompt)
|
| 130 |
+
refined = refine_answer(initial_answer, query, sources_text)
|
| 131 |
+
# Return refined answer along with the source information
|
| 132 |
+
return f"{refined}\n\nSources:\n{sources_text}"
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Flask==2.2.3
|
| 2 |
+
openai==0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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<title>Medical Chatbot</title>
|
| 6 |
+
<style>
|
| 7 |
+
body {
|
| 8 |
+
font-family: Arial, sans-serif;
|
| 9 |
+
margin: 0;
|
| 10 |
+
padding: 0;
|
| 11 |
+
background: #f8f9fa;
|
| 12 |
+
}
|
| 13 |
+
.container {
|
| 14 |
+
max-width: 600px;
|
| 15 |
+
margin: 40px auto;
|
| 16 |
+
background: #fff;
|
| 17 |
+
border-radius: 8px;
|
| 18 |
+
padding: 20px;
|
| 19 |
+
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
| 20 |
+
text-align: center;
|
| 21 |
+
}
|
| 22 |
+
.logo {
|
| 23 |
+
display: block;
|
| 24 |
+
margin: 0 auto 20px auto;
|
| 25 |
+
max-width: 180px;
|
| 26 |
+
}
|
| 27 |
+
h1 {
|
| 28 |
+
margin-bottom: 20px;
|
| 29 |
+
}
|
| 30 |
+
.tags {
|
| 31 |
+
display: flex;
|
| 32 |
+
flex-wrap: wrap;
|
| 33 |
+
gap: 10px;
|
| 34 |
+
margin-bottom: 20px;
|
| 35 |
+
justify-content: center;
|
| 36 |
+
}
|
| 37 |
+
.tag-button {
|
| 38 |
+
background-color: #ff7900;
|
| 39 |
+
color: #fff;
|
| 40 |
+
border: none;
|
| 41 |
+
border-radius: 4px;
|
| 42 |
+
padding: 8px 12px;
|
| 43 |
+
cursor: pointer;
|
| 44 |
+
}
|
| 45 |
+
.tag-button:hover {
|
| 46 |
+
background-color: #fb8c00;
|
| 47 |
+
}
|
| 48 |
+
.input-area {
|
| 49 |
+
display: flex;
|
| 50 |
+
gap: 10px;
|
| 51 |
+
justify-content: center;
|
| 52 |
+
margin-bottom: 20px;
|
| 53 |
+
}
|
| 54 |
+
input[type="text"] {
|
| 55 |
+
flex: 1;
|
| 56 |
+
padding: 10px;
|
| 57 |
+
border-radius: 4px;
|
| 58 |
+
border: 1px solid #ccc;
|
| 59 |
+
font-size: 1rem;
|
| 60 |
+
}
|
| 61 |
+
button.ask-btn {
|
| 62 |
+
background-color: #36afea;
|
| 63 |
+
color: white;
|
| 64 |
+
border: none;
|
| 65 |
+
border-radius: 4px;
|
| 66 |
+
padding: 10px 20px;
|
| 67 |
+
cursor: pointer;
|
| 68 |
+
}
|
| 69 |
+
button.ask-btn:hover {
|
| 70 |
+
background-color: #1587c1;
|
| 71 |
+
}
|
| 72 |
+
#answer {
|
| 73 |
+
white-space: pre-wrap;
|
| 74 |
+
margin-top: 20px;
|
| 75 |
+
padding: 10px;
|
| 76 |
+
background: #f1f1f1;
|
| 77 |
+
border-radius: 4px;
|
| 78 |
+
min-height: 50px;
|
| 79 |
+
text-align: left;
|
| 80 |
+
overflow-y: auto;
|
| 81 |
+
max-height: 300px;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/* Loading Spinner Style */
|
| 85 |
+
#loading {
|
| 86 |
+
display: none;
|
| 87 |
+
margin-top: 20px;
|
| 88 |
+
}
|
| 89 |
+
.spinner {
|
| 90 |
+
border: 4px solid #f3f3f3;
|
| 91 |
+
border-top: 4px solid #36afea;
|
| 92 |
+
border-radius: 50%;
|
| 93 |
+
width: 40px;
|
| 94 |
+
height: 40px;
|
| 95 |
+
animation: spin 1s linear infinite;
|
| 96 |
+
margin: 0 auto;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
@keyframes spin {
|
| 100 |
+
0% { transform: rotate(0deg); }
|
| 101 |
+
100% { transform: rotate(360deg); }
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
@media (max-width: 600px) {
|
| 105 |
+
.container {
|
| 106 |
+
width: 90%;
|
| 107 |
+
margin: 20px auto;
|
| 108 |
+
padding: 15px;
|
| 109 |
+
}
|
| 110 |
+
.input-area {
|
| 111 |
+
flex-direction: column;
|
| 112 |
+
align-items: stretch;
|
| 113 |
+
}
|
| 114 |
+
input[type="text"] {
|
| 115 |
+
width: 100%;
|
| 116 |
+
margin-bottom: 10px;
|
| 117 |
+
}
|
| 118 |
+
button.ask-btn {
|
| 119 |
+
width: 100%;
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
</style>
|
| 123 |
+
</head>
|
| 124 |
+
<body>
|
| 125 |
+
<div class="container">
|
| 126 |
+
<!-- Use a local file by placing your logo in the static folder -->
|
| 127 |
+
<img src="{{ url_for('static', filename='logo.png') }}" alt="Logo" class="logo" />
|
| 128 |
+
<h1>Medical Chatbot</h1>
|
| 129 |
+
<div class="tags">
|
| 130 |
+
<button class="tag-button" onclick="setQuestion('Menopause')">Menopause</button>
|
| 131 |
+
<button class="tag-button" onclick="setQuestion('Vaginal surgery')">Vaginal surgery</button>
|
| 132 |
+
<button class="tag-button" onclick="setQuestion('Hormones')">Hormones</button>
|
| 133 |
+
<button class="tag-button" onclick="setQuestion('High risk pregnancy')">High risk pregnancy</button>
|
| 134 |
+
<button class="tag-button" onclick="setQuestion('MTP')">MTP</button>
|
| 135 |
+
<button class="tag-button" onclick="setQuestion('Fetal medicine')">Fetal medicine</button>
|
| 136 |
+
</div>
|
| 137 |
+
<div class="input-area">
|
| 138 |
+
<input type="text" id="userQuestion" placeholder="Ask any question about the topic..." />
|
| 139 |
+
<button class="ask-btn" onclick="askQuestion()">Ask</button>
|
| 140 |
+
</div>
|
| 141 |
+
<!-- Updated Loading Spinner -->
|
| 142 |
+
<div id="loading">
|
| 143 |
+
<div class="spinner"></div> Loading...
|
| 144 |
+
</div>
|
| 145 |
+
<div id="answer"></div>
|
| 146 |
+
</div>
|
| 147 |
+
|
| 148 |
+
<script>
|
| 149 |
+
function setQuestion(topic) {
|
| 150 |
+
document.getElementById('userQuestion').value = topic;
|
| 151 |
+
}
|
| 152 |
+
async function askQuestion() {
|
| 153 |
+
const question = document.getElementById('userQuestion').value.trim();
|
| 154 |
+
if (!question) return;
|
| 155 |
+
document.getElementById('loading').style.display = 'block';
|
| 156 |
+
document.getElementById('answer').innerHTML = '';
|
| 157 |
+
try {
|
| 158 |
+
const response = await fetch('/ask', {
|
| 159 |
+
method: 'POST',
|
| 160 |
+
headers: { 'Content-Type': 'application/json' },
|
| 161 |
+
body: JSON.stringify({ question })
|
| 162 |
+
});
|
| 163 |
+
const data = await response.json();
|
| 164 |
+
document.getElementById('answer').innerHTML = data.answer;
|
| 165 |
+
} catch (error) {
|
| 166 |
+
document.getElementById('answer').textContent = 'Error retrieving answer.';
|
| 167 |
+
} finally {
|
| 168 |
+
document.getElementById('loading').style.display = 'none';
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
</script>
|
| 172 |
+
</body>
|
| 173 |
+
</html>
|