Spaces:
Sleeping
Sleeping
File size: 25,158 Bytes
ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 4030bd7 ca9145f 3dace8b ca9145f 3dace8b ca9145f | 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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 | # File: main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uuid
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import os
import httpx
from fastapi import HTTPException
from typing import Dict, Optional, Any
from datetime import datetime, timedelta
import json
import asyncio
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class SessionInit(BaseModel):
pass
class SessionData(BaseModel):
session_id: str
situation: str
thought: str
distortions: Optional[list] = None
analysis: Optional[dict] = None
candidates: Optional[list] = None
selected_reframe: Optional[dict] = None
created_at: datetime
updated_at: datetime
def clean_expired_sessions():
"""Remove sessions older than SESSION_EXPIRY_MINUTES"""
now = datetime.now()
expired = [
sid for sid, data in sessions_store.items()
if (now - data['updated_at']).seconds > SESSION_EXPIRY_MINUTES * 60
]
for sid in expired:
del sessions_store[sid]
def get_session(session_id: str) -> Optional[dict]:
"""Get session data by ID"""
clean_expired_sessions()
return sessions_store.get(session_id)
def update_session(session_id: str, data: dict):
"""Update session data"""
if session_id in sessions_store:
sessions_store[session_id].update(data)
sessions_store[session_id]['updated_at'] = datetime.now()
else:
raise HTTPException(status_code=404, detail="Session not found")
class DetectionRequest(BaseModel):
session_id: str
situation: str
thought: str
class AnalyzeRequest(BaseModel):
session_id: str
situation: str
thought: str
distortions: list
class ReframeRequest(BaseModel):
session_id: str
situation: str
thought: str
recommended_therapies: list
class FeedbackRequest(BaseModel):
session_id: str
situation: str
thought: str
current_reframe: str
class ImproveRequest(BaseModel):
session_id: str
situation: str
thought: str
current_reframe: str
history_response: list
feedback: str
API_base = 'http://localhost:1812/api/v1/'
sessions_store: Dict[str, dict] = {}
SESSION_EXPIRY_MINUTES = 60
class FeedbackData(BaseModel):
session_id: str
timestamp: str
input: dict
output: dict
ratings: dict
@app.post("/api/feedback")
async def save_feedback(data: FeedbackData):
try:
# Chuyển đổi sang dict
record = data.dict()
# Ghi vào file dataset_feedback.jsonl
# Mode 'a' (append) để ghi nối tiếp, không ghi đè
with open("dataset_feedback.jsonl", "a", encoding="utf-8") as f:
# Ghi mỗi feedback trên 1 dòng (JSONL format)
f.write(json.dumps(record, ensure_ascii=False) + "\n")
return {"status": "success", "message": "Feedback saved"}
except Exception as e:
print(f"Error saving file: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.post("/api/session/init")
async def init_session():
"""Initialize a new session"""
session_id = str(uuid.uuid4())
sessions_store[session_id] = {
'session_id': session_id,
'situation': None,
'thought': None,
'distortions': None,
'analysis': None,
'candidates': None,
'selected_reframe': None,
'created_at': datetime.now(),
'updated_at': datetime.now()
}
return {"session_id": session_id}
def _check_has_distortion(text: str) -> bool:
"""Kiểm tra xem có distortion hay không"""
if not text or len(text.strip()) < 10:
return False
# if '[' in text and ']' in text:
# return True
positive_indicators = [
"all-or-nothing", "mind reading", "catastrophizing",
"overgeneralization", "mental filter", "labeling",
"emotional reasoning", "should statements",
"jumping to conclusions", "fortune telling",
"personalization", "disqualifying"
]
text_lower = text.lower()
if any(indicator in text_lower for indicator in positive_indicators):
return True
negative_indicators = [
"không có distortion",
"không phát hiện distortion",
"no distortion",
"không tìm thấy distortion"
]
return not any(indicator in text_lower for indicator in negative_indicators)
def _extract_distortion_types(text: str) -> list:
"""
Extract các loại distortion từ response
Hỗ trợ format: [Type1, Type2, Type3] hoặc text tự do
"""
import re
bracket_match = re.search(r'\[(.*?)\]', text)
if bracket_match:
content = bracket_match.group(1)
distortions = [d.strip() for d in content.split(',')]
normalized = []
for d in distortions:
d_normalized = d.strip().title()
if 'all-or-nothing' in d.lower():
d_normalized = 'All-or-Nothing Thinking'
elif 'mind reading' in d.lower():
d_normalized = 'Mind Reading'
elif 'catastrophizing' in d.lower():
d_normalized = 'Catastrophizing'
elif 'overgeneralization' in d.lower():
d_normalized = 'Overgeneralization'
elif 'mental filter' in d.lower():
d_normalized = 'Mental Filter'
elif 'jumping to conclusions' in d.lower():
d_normalized = 'Jumping to Conclusions'
elif 'fortune telling' in d.lower():
d_normalized = 'Fortune Telling'
elif 'emotional reasoning' in d.lower():
d_normalized = 'Emotional Reasoning'
elif 'should statements' in d.lower():
d_normalized = 'Should Statements'
elif 'labeling' in d.lower():
d_normalized = 'Labeling'
elif 'personalization' in d.lower():
d_normalized = 'Personalization'
elif 'disqualifying the positive' in d.lower():
d_normalized = 'Disqualifying the Positive'
elif 'magnification' in d.lower():
d_normalized = 'Magnification'
elif 'minimization' in d.lower():
d_normalized = 'Minimization'
elif 'blame' in d.lower():
d_normalized = 'Blame'
normalized.append(d_normalized)
return normalized if normalized else ["Unknown Distortion"]
common_distortions = {
"all-or-nothing": "All-or-Nothing Thinking",
"overgeneralization": "Overgeneralization",
"mental filter": "Mental Filter",
"disqualifying the positive": "Disqualifying the Positive",
"jumping to conclusions": "Jumping to Conclusions",
"mind reading": "Mind Reading",
"fortune telling": "Fortune Telling",
"magnification": "Magnification",
"catastrophizing": "Catastrophizing",
"minimization": "Minimization",
"emotional reasoning": "Emotional Reasoning",
"should statements": "Should Statements",
"labeling": "Labeling",
"personalization": "Personalization",
"blame": "Blame"
}
found_distortions = []
text_lower = text.lower()
for key, distortion_name in common_distortions.items():
if key in text_lower:
found_distortions.append(distortion_name)
seen = set()
unique_distortions = []
for d in found_distortions:
if d not in seen:
seen.add(d)
unique_distortions.append(d)
return unique_distortions if unique_distortions else ["Unknown Distortion"]
def _extract_explanation(text: str) -> str:
"""
Extract phần giải thích từ response
Bỏ qua phần danh sách distortions trong []
"""
import re
text_cleaned = re.sub(r'^\s*\[.*?\]\s*', '', text).strip()
if text_cleaned:
explanation = text_cleaned.strip()
prefixes_to_remove = [
"explanation:",
"giải thích:",
"phân tích:"
# "the speaker"
]
explanation_lower = explanation.lower()
for prefix in prefixes_to_remove:
if explanation_lower.startswith(prefix):
explanation = explanation[len(prefix):].strip()
if explanation:
explanation = explanation[0].upper() + explanation[1:]
break
return explanation
return text.strip()
@app.post("/api/detect")
async def detect_distortion(request: DetectionRequest):
try:
update_session(request.session_id, {
'situation': request.situation,
'thought': request.thought
})
async with httpx.AsyncClient(timeout=30.0) as client:
dot_analysis = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": "dot.analysis",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
dot_analysis.raise_for_status()
result_analysis = dot_analysis.json()
analysis_response = result_analysis.get("result", "") or result_analysis.get("content", "") # Fix: đổi result thành result_analysis
# Bước 2: Gọi dot.detection với kết quả từ dot.analysis
dot_detection = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": "dot.detection",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
"dot_analysis": analysis_response
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
dot_detection.raise_for_status()
result_detection = dot_detection.json() # Fix: đổi tên biến để rõ ràng
ai_response = result_detection.get("result", "") or result_detection.get("content", "") # Fix: dùng result_detection
has_distortion = _check_has_distortion(ai_response)
distortion_types = _extract_distortion_types(ai_response)
explanation = _extract_explanation(ai_response)
update_session(request.session_id, {
'distortions': distortion_types if distortion_types else []
})
return {
"session_id": request.session_id,
"has_distortion": has_distortion,
"distortion_types": distortion_types,
"explanation": explanation,
"raw_response": ai_response
}
except httpx.HTTPError as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi khi gọi API phân tích: {str(e)}"
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi không xác định: {str(e)}"
)
def _parse_json_response(text: str) -> dict:
"""Parse JSON từ AI response, xử lý markdown và whitespace"""
import json
import re
try:
# Clean text
text = text.strip()
# Remove markdown code blocks
if text.startswith("```json"):
text = text[7:]
elif text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
# Parse JSON
return json.loads(text)
except json.JSONDecodeError as e:
# Fallback: try to extract JSON from text
json_match = re.search(r'\{.*\}', text, re.DOTALL)
if json_match:
try:
return json.loads(json_match.group())
except:
pass
raise ValueError(f"Không thể parse JSON response: {e}\nText: {text[:200]}")
@app.post("/api/analyze")
async def analyze_thought(request: AnalyzeRequest):
try:
async with httpx.AsyncClient(timeout=30.0) as client:
thera_rcm = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": "dot.thera_rcm",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
"distortions_type": request.distortions
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
thera_rcm.raise_for_status()
result = thera_rcm.json()
print(request.situation)
print(request.thought)
print(request.distortions)
ai_text = result.get("result", "") or result.get("content", "")
parsed_result = _parse_json_response(ai_text)
# Validate và add defaults nếu thiếu fields
if "emotional_impact" not in parsed_result:
parsed_result["emotional_impact"] = "Tác động cảm xúc đáng kể"
if "underlying_beliefs" not in parsed_result or not parsed_result["underlying_beliefs"]:
parsed_result["underlying_beliefs"] = ["Niềm tin cốt lõi cần được khám phá thêm"]
if "triggers" not in parsed_result or not parsed_result["triggers"]:
parsed_result["triggers"] = ["Các tình huống tương tự"]
if "recommended_therapies" not in parsed_result or not parsed_result["recommended_therapies"]:
# Default therapies based on common distortions
parsed_result["recommended_therapies"] = ["CBT", "ACT"]
parsed_result["session_id"] = request.session_id
return parsed_result
except json.JSONDecodeError as e:
# Fallback response nếu parse JSON thất bại
return {
"session_id": request.session_id,
"emotional_impact": "Lo âu và căng thẳng đáng kể do các suy nghĩ tiêu cực",
"underlying_beliefs": [
"Tôi cần được chấp nhận bởi người khác",
"Tôi phải tránh thất bại bằng mọi giá",
"Nếu có vấn đề xảy ra, đó là lỗi của tôi"
],
"triggers": [
"Tình huống liên quan đến mối quan hệ",
"Áp lực và kỳ vọng",
"Sự không chắc chắn"
],
"recommended_therapies": ["CBT", "ACT", "DBT"]
}
except httpx.HTTPError as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi khi gọi API phân tích: {str(e)}"
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi không xác định: {str(e)}"
)
# @app.post("/api/reframe")
# async def generate_reframe(request: ReframeRequest):
# reframe_candidates = []
# for therapy in request.recommended_therapies:
# async with httpx.AsyncClient(timeout=30.0) as client:
# response = await client.post(
# f"{API_base}prompts/templates/execute",
# json={
# "provider": "groq",
# "template_name": f"reframe.{therapy.lower()}",
# "model": "openai/gpt-oss-20b",
# "variables": {
# "situation": request.situation,
# "thought": request.thought,
# }
# },
# headers={
# "accept": "application/json",
# "Content-Type": "application/json"
# }
# )
# response.raise_for_status()
# result = response.json()
# reframe = result.get("reframing response", "")
# # parsed_result = _parse_json_response(ai_text)
# reframe_candidates.append({
# "therapy": f"{therapy}",
# "reframe": f"{reframe}",
# "rationale": "demo",
# "evaluation": {"empathy": 5, "logic": 4, "helpfulness": 5}
# })
# return reframe_candidates
@app.post("/api/reframe")
async def generate_reframe(request: ReframeRequest):
async def fetch_reframe(therapy: str) -> Dict[str, Any]:
"""Fetch reframe for a single therapy type"""
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": f"reframe.{therapy.lower()}",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()
result = response.json()
# Parse JSON string trong trường 'content'
import json
content_str = result.get("content", "{}")
content_json = json.loads(content_str)
# Thử cả 2 key có thể có
reframe = content_json.get("reframing response") or content_json.get("reframing_response", "")
wtw = content_json.get("why_this_works") or content_json.get("why this works", "")
feedback = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": f"dot.thera_supervisor",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
"reframe_response": reframe
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
feedback.raise_for_status()
feedback = feedback.json()
print(feedback)
feedback_str = feedback.get("content", "{}")
feedback_json = json.loads(feedback_str)
return {
"therapy": therapy,
"reframe": reframe,
"rationale": wtw,
"evaluation": feedback_json
}
reframe_candidates = await asyncio.gather(
*[fetch_reframe(therapy) for therapy in request.recommended_therapies],
return_exceptions=True
)
successful_results = [
result for result in reframe_candidates
if not isinstance(result, Exception)
]
return {
"session_id": request.session_id,
"candidates": successful_results
}
@app.post("/api/instruction_feedback")
async def generate_instruction_feedback(request: FeedbackRequest):
try:
async with httpx.AsyncClient(timeout=30.0) as client:
ai_feedback = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": "reframe.thera_supervisor_full",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
"reframe_response": request.current_reframe
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
ai_feedback.raise_for_status()
ai_feedback = ai_feedback.json()
ai_feedback = ai_feedback.get("result", "") or ai_feedback.get("content", "")
return {
"session_id": request.session_id,
"ai_feedback": ai_feedback,
}
except httpx.HTTPError as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi khi gọi API phân tích: {str(e)}"
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi không xác định: {str(e)}"
)
@app.post("/api/improve")
async def generate_improve_reframe(request: ImproveRequest):
try:
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": "reframe.cbtwfeedback",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
"history_response": request.history_response,
"old_response": request.current_reframe,
"feedback": request.feedback
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()
result = response.json()
import json
content_str = result.get("content", "{}")
content_json = json.loads(content_str)
reframe = content_json.get("reframing response") or content_json.get("reframing_response", "")
ai_feedback = await client.post(
f"{API_base}prompts/templates/execute",
json={
"provider": "openai",
"template_name": "reframe.thera_supervisor_full",
"model": "gpt-4.1",
"variables": {
"situation": request.situation,
"thought": request.thought,
"reframe_response": reframe
}
},
headers={
"accept": "application/json",
"Content-Type": "application/json"
}
)
ai_feedback.raise_for_status()
ai_feedback = ai_feedback.json()
ai_feedback = ai_feedback.get("result", "") or ai_feedback.get("content", "")
return {
"session_id": request.session_id,
"new_reframe": reframe,
"ai_feedback": ai_feedback
}
except httpx.HTTPError as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi khi gọi API phân tích: {str(e)}"
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Lỗi không xác định: {str(e)}"
)
@app.post("/api/save")
async def save_selection(data: dict):
print(f"User saved reframe: {data}")
return {"status": "success"}
app.mount("/assets", StaticFiles(directory="../mind-reframe/dist/assets"), name="assets")
@app.get("/{full_path:path}")
async def serve_react_app(full_path: str):
if full_path.startswith("api/"):
return {"error": "Not Found"}
return FileResponse("../mind-reframe/dist/index.html") |