Download server.py from yellowmug/mindily: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/spaces/yellowmug/mindily/resolve/main/server.py
- Command line
-
hf download hf://spaces/yellowmug/mindily/server.py
-
curl -L -o server.py https://huggingface.co/spaces/yellowmug/mindily/resolve/main/server.py
13.7 kB
| """Mindily: 실제 감정 분류 API와 동일 출처의 UI 제공.""" | |
| import os | |
| import re | |
| from pathlib import Path | |
| from contextlib import asynccontextmanager | |
| from threading import Lock | |
| from urllib.parse import urlparse | |
| ROOT = Path(__file__).resolve().parent | |
| os.environ.setdefault('HF_HOME', str(ROOT / 'models' / 'cache')) | |
| os.environ.setdefault('HF_HUB_DISABLE_TELEMETRY', '1') | |
| import torch | |
| import httpx | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.staticfiles import StaticFiles | |
| import mimetypes | |
| # 일부 환경에서 .webmanifest MIME 타입이 없어 설치 배너가 뜨지 않는다. | |
| mimetypes.add_type('application/manifest+json', '.webmanifest') | |
| from pydantic import BaseModel, Field, field_validator | |
| from typing import Optional | |
| from feedback_db import save_feedback | |
| from memory_db import remember, recall, forget | |
| from coach_agent import run_coach_agent | |
| from rag import answer_with_grounding, retrieve_activities, retrieve_grounding | |
| from comfort_knowledge import comfort_for | |
| from diary_draft import organizer_draft, report_events | |
| from safety import crisis_support, has_crisis_signal | |
| import llm | |
| MODEL = os.getenv('MINDILY_MODEL_PATH', 'GGARA02/kcelectra-korean-emotion') | |
| REVISION = '2eaf89d8d2cbfd902b93e5ec989db2ec103806fb' | |
| inference_lock = Lock() | |
| async def lifespan(app): | |
| offline = os.getenv('MINDILY_OFFLINE') == '1' | |
| model_source = Path(MODEL) | |
| load_args = {'local_files_only': offline} | |
| if not model_source.exists(): | |
| load_args['revision'] = REVISION | |
| app.state.tokenizer = AutoTokenizer.from_pretrained(MODEL, **load_args) | |
| app.state.model = AutoModelForSequenceClassification.from_pretrained( | |
| MODEL, **load_args, use_safetensors=True | |
| ).eval() | |
| yield | |
| app = FastAPI(lifespan=lifespan) | |
| class Diary(BaseModel): | |
| text: str = Field(min_length=1, max_length=1000) | |
| self_reported_stress: int = Field(ge=1, le=5, strict=True) | |
| def nonblank(cls, value): | |
| if not value.strip(): | |
| raise ValueError('일기를 입력해주세요.') | |
| return value.strip() | |
| class AgentRequest(Diary): | |
| context: str = Field(default='diary', pattern='^(diary|chat)$') | |
| memory_token: Optional[str] = Field(default=None, min_length=32, max_length=128) | |
| known_emotion: Optional[str] = Field(default=None, pattern='^(불안|슬픔|분노|기쁨|상처|당황)$') | |
| class HealingRequest(BaseModel): | |
| emotion: str = Field(min_length=1, max_length=30) | |
| stress: int = Field(ge=1, le=5, strict=True) | |
| minutes: int = Field(default=5, ge=1, le=120, strict=True) | |
| allow_location: bool = False | |
| memory_token: Optional[str] = Field(default=None, min_length=32, max_length=128) | |
| class MemoryRequest(BaseModel): | |
| token: str = Field(min_length=32, max_length=128) | |
| class MemorySave(MemoryRequest): | |
| preferred_kind: str = Field(pattern='^(호흡|감각활동|자연의 소리|걷기)$') | |
| consent: bool | |
| class Feedback(BaseModel): | |
| card_id: str = Field(min_length=1, max_length=80) | |
| helpful: Optional[bool] = None | |
| satisfaction: Optional[int] = Field(default=None, ge=1, le=5, strict=True) | |
| comment: Optional[str] = Field(default=None, max_length=300) | |
| consent: bool = False | |
| class AppRating(BaseModel): | |
| client_id: str = Field(pattern=r'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$') | |
| submission_id: str = Field(pattern=r'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$') | |
| design: int = Field(ge=1, le=5, strict=True) | |
| emotion_helpfulness: int = Field(ge=1, le=5, strict=True) | |
| continued_use: int = Field(ge=1, le=5, strict=True) | |
| improvement: str = Field(min_length=1, max_length=500) | |
| consent: bool = False | |
| def nonblank_improvement(cls, value): | |
| if not value.strip(): | |
| raise ValueError('개선하면 좋을 점을 한 가지 적어주세요.') | |
| return value.strip() | |
| class OrganizerDraftRequest(BaseModel): | |
| text: str = Field(min_length=1, max_length=1000) | |
| emotion: str = Field(default='', max_length=30) | |
| consent: bool = False | |
| class ReportEventEntry(BaseModel): | |
| id: str = Field(min_length=1, max_length=80) | |
| date: str = Field(min_length=1, max_length=30) | |
| emotion: str = Field(default='감정 미기록', max_length=30) | |
| text: str = Field(min_length=1, max_length=1000) | |
| class ReportEventsRequest(BaseModel): | |
| entries: list[ReportEventEntry] = Field(min_length=1, max_length=10) | |
| consent: bool = False | |
| def health(): | |
| return {'status': 'ready', 'model': MODEL, | |
| 'revision': REVISION if not Path(MODEL).exists() else 'local-fine-tuned', | |
| 'generation': llm.status()} | |
| def llm_status(): | |
| """생성형 경로의 활성 여부와 접지 정책을 공개한다. API 키는 노출하지 않는다.""" | |
| return llm.status() | |
| def analyze(diary: Diary): | |
| if not inference_lock.acquire(blocking=False): | |
| raise HTTPException(503, '다른 분석을 진행 중이에요. 잠시 후 다시 시도해주세요.') | |
| try: | |
| tokenizer = app.state.tokenizer | |
| # 모든 입력을 읽되, 학습 길이에 맞춰 128토큰 단위로 분할한다. | |
| encoded = tokenizer(diary.text, truncation=True, max_length=128, | |
| return_overflowing_tokens=True, padding=True, return_tensors='pt') | |
| encoded.pop('overflow_to_sample_mapping', None) | |
| with torch.inference_mode(): | |
| chunk_scores = app.state.model(**encoded).logits.softmax(-1) | |
| weights = (encoded['attention_mask'].sum(-1) - 2).clamp(min=1) | |
| scores = (chunk_scores * weights[:, None]).sum(0) / weights.sum() | |
| labels = sorted([{'name': app.state.model.config.id2label[i], 'score': float(s)} | |
| for i, s in enumerate(scores)], key=lambda x: x['score'], reverse=True) | |
| return {'model': MODEL, 'revision': REVISION if not Path(MODEL).exists() else 'local-fine-tuned', 'labels': labels, | |
| 'self_reported_stress': diary.self_reported_stress, | |
| 'chunks': len(chunk_scores), 'aggregation': 'token_weighted_mean', | |
| 'disclaimer': '분류 점수는 실제 감정 비율이 아니에요. 최종 마음은 직접 선택해주세요.'} | |
| finally: | |
| inference_lock.release() | |
| def recommend_healing(request: HealingRequest): | |
| """Retrieve sourced activities; location lookup is not implemented yet.""" | |
| preferred = recall(request.memory_token) if request.memory_token else None | |
| cards = retrieve_activities( | |
| request.emotion, request.stress, request.minutes, preferred) | |
| return {'tool': 'recommend_healing', 'emotion': request.emotion, | |
| 'stress': request.stress, 'cards': cards, | |
| 'location_available': False, 'personalized': bool(preferred), | |
| 'preferred_kind': preferred} | |
| def rag_search(request: HealingRequest): | |
| """Return source chunks selected for a grounded response.""" | |
| preferred = recall(request.memory_token) if request.memory_token else None | |
| return {'tool': 'retrieve_grounding', 'emotion': request.emotion, | |
| 'stress': request.stress, 'sources': retrieve_grounding( | |
| request.emotion, request.stress, request.minutes, preferred), | |
| 'personalized': bool(preferred), 'preferred_kind': preferred} | |
| def rag_answer(request: HealingRequest): | |
| """Return a grounded fallback answer and its source context.""" | |
| preferred = recall(request.memory_token) if request.memory_token else None | |
| return {'tool': 'rag_answer', 'emotion': request.emotion, | |
| 'stress': request.stress, **answer_with_grounding( | |
| request.emotion, request.stress, request.minutes, preferred)} | |
| def coach(request: AgentRequest): | |
| """Route a diary or chat turn through the real model and sourced activity tool.""" | |
| if has_crisis_signal(request.text): | |
| safety = crisis_support() | |
| return { | |
| 'intent': 'safety', | |
| 'message': safety['message'], | |
| 'response_type': 'safety', | |
| 'generation': 'not_run', | |
| 'analysis': None, | |
| 'recommendation': None, | |
| 'grounding': None, | |
| 'comfort': None, | |
| 'tool_trace': [{'tool': 'crisis_safety', 'status': 'completed'}], | |
| 'disclaimer': 'Mindily는 위기 상담이나 의료적 진단을 대신하지 않아요.', | |
| 'safety': safety, | |
| } | |
| result = run_coach_agent( | |
| request.text, request.self_reported_stress, request.context, request.memory_token, | |
| lambda text, stress: analyze(Diary(text=text, self_reported_stress=stress)), | |
| lambda emotion, stress, token: recommend_healing( | |
| HealingRequest(emotion=emotion, stress=stress, minutes=20, memory_token=token)), | |
| request.known_emotion, | |
| lambda emotion, stress, preferred: answer_with_grounding( | |
| emotion, stress, minutes=20, preferred_kind=preferred), | |
| ) | |
| analysis = result.get('analysis') | |
| lead = analysis['labels'][0]['name'] if analysis else (request.known_emotion or '불안') | |
| result['comfort'] = comfort_for(lead) | |
| return result | |
| def create_organizer_draft(request: OrganizerDraftRequest): | |
| if not request.consent: | |
| raise HTTPException(422, '일기 내용으로 초안을 만드는 데 동의해 주세요.') | |
| return organizer_draft(request.text.strip(), request.emotion.strip()) | |
| def create_report_events(request: ReportEventsRequest): | |
| if not request.consent: | |
| raise HTTPException(422, '일기 내용으로 사건 요약을 만드는 데 동의해 주세요.') | |
| return report_events([entry.model_dump() for entry in request.entries]) | |
| def save_memory(request: MemorySave): | |
| if not request.consent: | |
| raise HTTPException(422, '기억 저장 동의가 필요해요.') | |
| remember(request.token, request.preferred_kind) | |
| return {'saved': True, 'preferred_kind': request.preferred_kind} | |
| def read_memory(request: MemoryRequest): | |
| return {'preferred_kind': recall(request.token)} | |
| def delete_memory(request: MemoryRequest): | |
| return {'deleted': forget(request.token)} | |
| def save_user_feedback(feedback: Feedback): | |
| """Store consented feedback in SQLite; diary text and location are never included.""" | |
| if not feedback.consent: | |
| return {'tool': 'save_user_feedback', 'saved': False, | |
| 'message': '동의하지 않아 저장하지 않았어요.'} | |
| if feedback.satisfaction is None and feedback.helpful is None: | |
| raise HTTPException(422, '만족도 또는 도움됨 평가를 선택해주세요.') | |
| helpful = feedback.helpful if feedback.helpful is not None else feedback.satisfaction >= 4 | |
| receipt = save_feedback(feedback.card_id, helpful, feedback.satisfaction, feedback.comment) | |
| return {'tool': 'save_user_feedback', 'saved': True, | |
| 'receipt': receipt, 'message': '의견을 저장했어요.'} | |
| def save_app_rating(rating: AppRating): | |
| """Let the sheet assign a stable participant code to this browser.""" | |
| if not rating.consent: | |
| raise HTTPException(422, '구글 시트 저장 동의가 필요해요.') | |
| webhook_url = os.getenv('MINDILY_SURVEY_WEBHOOK_URL', '').strip() | |
| parsed = urlparse(webhook_url) | |
| if parsed.scheme != 'https' or parsed.hostname != 'script.google.com' or not parsed.path.startswith('/macros/s/') or not parsed.path.endswith('/exec'): | |
| raise HTTPException(503, '구글 시트 연결이 아직 준비되지 않았어요.') | |
| payload = { | |
| 'client_id': rating.client_id, | |
| 'submission_id': rating.submission_id, | |
| 'design': rating.design, | |
| 'emotion_helpfulness': rating.emotion_helpfulness, | |
| 'continued_use': rating.continued_use, | |
| 'improvement': rating.improvement, | |
| } | |
| try: | |
| with httpx.Client(timeout=15, follow_redirects=True) as client: | |
| response = client.post(webhook_url, json=payload) | |
| response.raise_for_status() | |
| result = response.json() | |
| except (httpx.HTTPError, ValueError) as exc: | |
| raise HTTPException(502, '구글 시트의 저장 응답을 확인하지 못했어요.') from exc | |
| if not isinstance(result, dict) or result.get('saved') is not True: | |
| raise HTTPException(502, '구글 시트에서 저장 완료를 확인하지 못했어요.') | |
| participant_code = str(result.get('participant_code', '')) | |
| return { | |
| 'saved': True, | |
| 'participant_code': participant_code if re.fullmatch(r'U\d{2,}', participant_code) else None, | |
| } | |
| async def no_cache_for_shell(request, call_next): | |
| """index.html과 sw.js는 항상 재검증시킨다. | |
| 배포 후에도 브라우저가 옛 화면을 보여주는 사고를 막기 위함이다. | |
| 해시나 버전 표식이 붙는 자원(app.js?v=…)은 그대로 캐시해도 안전하다. | |
| """ | |
| response = await call_next(request) | |
| path = request.url.path | |
| if path in ('/', '/index.html', '/sw.js') or path.startswith('/api/'): | |
| response.headers['Cache-Control'] = 'no-cache, must-revalidate' | |
| return response | |
| app.mount('/', StaticFiles(directory=ROOT / 'dist', html=True), name='ui') | |