-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_app.py
More file actions
407 lines (336 loc) · 13.4 KB
/
web_app.py
File metadata and controls
407 lines (336 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import base64
import csv
import os
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from uuid import uuid4
def ensure_project_venv():
project_root = Path(__file__).resolve().parent
venv_python = project_root / "venv" / "Scripts" / "python.exe"
current_python = Path(sys.executable).resolve()
if not venv_python.exists() or current_python == venv_python.resolve():
return
subprocess.run([str(venv_python), str(project_root / "web_app.py")], check=False)
raise SystemExit
ensure_project_venv()
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from chatbot_ai import (
MAX_HISTORY_TURNS,
OUTSIDE_KNOWLEDGE_MESSAGE,
analyze_uploaded_report,
extract_document_text,
generate_response,
is_document_in_social_anxiety_scope,
normalize_user_message,
)
app = FastAPI(title="MindEase AI Assistant")
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
CHAT_SESSIONS = {}
SESSION_COOKIE_NAME = os.getenv("SESSION_COOKIE_NAME", "mindease_session_id")
ALLOWED_DOCUMENT_SUFFIXES = {".pdf", ".txt", ".md"}
ANALYTICS_DIR = Path("analytics")
METRICS_CSV_PATH = ANALYTICS_DIR / "chat_metrics.csv"
METRICS_FIELDNAMES = [
"timestamp_utc",
"session_id",
"input_type",
"complexity",
"question_chars",
"question_words",
"answer_chars",
"response_time_seconds",
"preprocessing_duration_seconds",
"accuracy_score",
"has_document",
"has_audio",
]
def trim_history(history):
if not history:
return []
max_messages = MAX_HISTORY_TURNS * 2
return history[-max_messages:]
def get_session_id(request: Request):
return request.cookies.get(SESSION_COOKIE_NAME) or uuid4().hex
def get_history(session_id):
return CHAT_SESSIONS.get(session_id, [])
def is_allowed_document(filename):
suffix = Path(filename).suffix.lower()
return suffix in ALLOWED_DOCUMENT_SUFFIXES
def round_seconds(start_time):
return round(max(time.perf_counter() - start_time, 0.0), 2)
def resolve_input_type(*, input_mode="", has_document=False, has_audio=False):
normalized = (input_mode or "").strip().lower()
if normalized in {"text", "voice", "document"}:
return normalized.title()
if has_document:
return "Document"
if has_audio:
return "Voice"
return "Text"
def classify_query_complexity(user_text, *, has_document=False, document_text_length=0):
message = (user_text or "").strip()
words = [token for token in message.split() if token]
word_count = len(words)
char_count = len(message)
if has_document and not message:
if document_text_length >= 4500:
return "Complex"
if document_text_length >= 1800:
return "Medium"
return "Simple"
if word_count >= 20 or char_count >= 130:
return "Complex"
if word_count >= 9 or char_count >= 55:
return "Medium"
if has_document and (word_count >= 6 or char_count >= 35):
return "Medium"
return "Simple"
def append_metrics_row(row):
try:
ANALYTICS_DIR.mkdir(parents=True, exist_ok=True)
file_exists = METRICS_CSV_PATH.exists()
with METRICS_CSV_PATH.open("a", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=METRICS_FIELDNAMES)
if not file_exists:
writer.writeheader()
writer.writerow(row)
except Exception:
# Metrics logging should never break normal chatbot responses.
pass
def estimate_project_accuracy(*, has_document=False, has_audio=False, question="", transcript="", answer=""):
user_text = (question or transcript or "").strip()
answer_text = (answer or "").strip()
question_words = [word for word in user_text.lower().split() if word]
answer_words = [word for word in answer_text.lower().split() if word]
question_word_count = len(question_words)
answer_word_count = len(answer_words)
question_unique_ratio = (
len(set(question_words)) / question_word_count
if question_word_count else 0.0
)
answer_unique_ratio = (
len(set(answer_words)) / answer_word_count
if answer_word_count else 0.0
)
accuracy_score = 58
accuracy_score += min(len(user_text) // 12, 12)
accuracy_score += min(len(answer_text) // 80, 14)
accuracy_score += min(question_word_count // 4, 6)
accuracy_score += min(answer_word_count // 25, 8)
if question_unique_ratio >= 0.75:
accuracy_score += 5
elif question_unique_ratio >= 0.55:
accuracy_score += 3
if answer_unique_ratio >= 0.72:
accuracy_score += 5
elif answer_unique_ratio >= 0.55:
accuracy_score += 3
if "?" in user_text:
accuracy_score += 2
if "\n" in answer_text:
accuracy_score += 2
if has_document and question:
accuracy_score += 8
elif has_document:
accuracy_score += 5
if has_audio:
accuracy_score -= 3
low_confidence_phrases = (
"i'm not sure",
"i am not sure",
"try again",
"could not",
"wasn't able",
"was not able",
"unavailable right now",
"error",
)
if any(phrase in answer_text.lower() for phrase in low_confidence_phrases):
accuracy_score -= 18
if len(user_text) < 12:
accuracy_score -= 6
accuracy_score = max(52, min(98, accuracy_score))
return round(accuracy_score / 100, 2)
@app.get("/")
async def index(request: Request):
session_id = get_session_id(request)
response = templates.TemplateResponse("index.html", {"request": request})
response.set_cookie(SESSION_COOKIE_NAME, session_id, httponly=True, samesite="lax")
return response
@app.post("/api/chat")
@app.post("/chat")
async def chat(request: Request):
request_started_at = time.perf_counter()
payload = await request.json()
question = (payload.get("question") or "").strip()
input_mode = (payload.get("input_mode") or "").strip()
audio_base64 = payload.get("audio_base64") or ""
audio_filename = (payload.get("audio_filename") or "voice.webm").strip() or "voice.webm"
document_base64 = payload.get("document_base64") or ""
document_filename = (payload.get("document_filename") or "report.pdf").strip() or "report.pdf"
temp_audio_path = None
temp_document_path = None
transcript = ""
stored_user_content = question
query_text_for_metrics = question
document_text_length = 0
preprocessing_duration_seconds = 0.0
response_time_seconds = 0.0
if not question and not audio_base64 and not document_base64:
return JSONResponse({"error": "Please type a message, record audio, or upload a report."}, status_code=400)
session_id = get_session_id(request)
history = get_history(session_id)
try:
user_input = question
if document_base64:
if not is_allowed_document(document_filename):
return JSONResponse(
{"error": "Sirf social anxiety se related PDF, TXT, ya MD files upload ki ja sakti hain."},
status_code=400,
)
try:
document_bytes = base64.b64decode(document_base64)
except Exception:
return JSONResponse({"error": "Document file could not be processed."}, status_code=400)
doc_suffix = Path(document_filename).suffix.lower() or ".pdf"
with tempfile.NamedTemporaryFile(delete=False, suffix=doc_suffix) as temp_file:
temp_file.write(document_bytes)
temp_document_path = temp_file.name
extracted_document_text = extract_document_text(temp_document_path)
if not extracted_document_text:
return JSONResponse({"error": "I could not extract readable text from that file."}, status_code=400)
document_text_length = len(extracted_document_text)
is_in_scope = await is_document_in_social_anxiety_scope(
extracted_document_text,
filename=document_filename,
)
if not is_in_scope:
return JSONResponse({"error": OUTSIDE_KNOWLEDGE_MESSAGE}, status_code=400)
if question:
user_input = {
"text": question,
"document_text": extracted_document_text,
"document_name": document_filename,
}
preprocessing_duration_seconds = round_seconds(request_started_at)
answer = await generate_response(user_input, history)
stored_user_content = f"{question}\n[Document: {document_filename}]"
else:
preprocessing_duration_seconds = round_seconds(request_started_at)
answer = await analyze_uploaded_report(
temp_document_path,
document_filename,
history,
extracted_text=extracted_document_text,
)
stored_user_content = f"[Report: {document_filename}]"
elif audio_base64:
try:
audio_bytes = base64.b64decode(audio_base64)
except Exception:
return JSONResponse({"error": "Audio file could not be processed."}, status_code=400)
suffix = Path(audio_filename).suffix or ".webm"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
temp_file.write(audio_bytes)
temp_audio_path = temp_file.name
transcript, validation_error = await normalize_user_message({
"text": "",
"files": [{"path": temp_audio_path, "name": audio_filename}],
})
if validation_error:
return JSONResponse({"error": validation_error}, status_code=400)
user_input = transcript
query_text_for_metrics = transcript
preprocessing_duration_seconds = round_seconds(request_started_at)
answer = await generate_response(user_input, history)
stored_user_content = transcript or "[Voice message]"
else:
preprocessing_duration_seconds = round_seconds(request_started_at)
answer = await generate_response(user_input, history)
stored_user_content = question
except Exception:
return JSONResponse(
{"error": "I ran into an AI response error. Please try again."},
status_code=500,
)
finally:
if temp_audio_path:
try:
os.remove(temp_audio_path)
except OSError:
pass
if temp_document_path:
try:
os.remove(temp_document_path)
except OSError:
pass
history.extend([
{"role": "user", "content": stored_user_content},
{"role": "assistant", "content": answer},
])
CHAT_SESSIONS[session_id] = trim_history(history)
response_time_seconds = round_seconds(request_started_at)
project_accuracy = estimate_project_accuracy(
has_document=bool(document_base64),
has_audio=bool(audio_base64),
question=question,
transcript=transcript,
answer=answer,
)
accuracy_score = int(round(project_accuracy * 100))
input_type = resolve_input_type(
input_mode=input_mode,
has_document=bool(document_base64),
has_audio=bool(audio_base64),
)
effective_user_text = (query_text_for_metrics or transcript or question or "").strip()
complexity = classify_query_complexity(
effective_user_text,
has_document=bool(document_base64),
document_text_length=document_text_length,
)
append_metrics_row({
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
"session_id": session_id,
"input_type": input_type,
"complexity": complexity,
"question_chars": len(effective_user_text),
"question_words": len([token for token in effective_user_text.split() if token]),
"answer_chars": len((answer or "").strip()),
"response_time_seconds": response_time_seconds,
"preprocessing_duration_seconds": preprocessing_duration_seconds,
"accuracy_score": accuracy_score,
"has_document": bool(document_base64),
"has_audio": bool(audio_base64),
})
response = JSONResponse({
"question": question,
"answer": answer,
"user_message": stored_user_content,
"transcript": transcript,
"project_accuracy": project_accuracy,
"accuracy_score": accuracy_score,
"preprocessing_duration_seconds": preprocessing_duration_seconds,
"response_time_seconds": response_time_seconds,
})
response.set_cookie(SESSION_COOKIE_NAME, session_id, httponly=True, samesite="lax")
return response
@app.post("/api/reset")
@app.post("/reset")
async def reset_chat(request: Request):
session_id = get_session_id(request)
CHAT_SESSIONS[session_id] = []
response = JSONResponse({"ok": True})
response.set_cookie(SESSION_COOKIE_NAME, session_id, httponly=True, samesite="lax")
return response
if __name__ == "__main__":
import uvicorn
uvicorn.run("web_app:app", host="127.0.0.1", port=7860, reload=True)