Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from fastapi.responses import HTMLResponse
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
from fastapi.templating import Jinja2Templates
|
| 5 |
+
import os
|
| 6 |
+
from huggingface_hub import InferenceClient
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Statische Dateien (CSS, JS) einbinden
|
| 11 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 12 |
+
templates = Jinja2Templates(directory="templates")
|
| 13 |
+
|
| 14 |
+
# HF-Token aus Umgebungsvariable
|
| 15 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 16 |
+
|
| 17 |
+
@app.get("/", response_class=HTMLResponse)
|
| 18 |
+
async def root(request: Request):
|
| 19 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 20 |
+
|
| 21 |
+
@app.post("/analyze")
|
| 22 |
+
async def analyze_text(request: Request):
|
| 23 |
+
data = await request.json()
|
| 24 |
+
user_text = data.get("text", "")
|
| 25 |
+
|
| 26 |
+
# Sentiment-Analyse durchführen
|
| 27 |
+
client = InferenceClient(token=HF_TOKEN)
|
| 28 |
+
sentiment = client.text_classification(
|
| 29 |
+
text=user_text,
|
| 30 |
+
model="cardiffnlp/twitter-roberta-base-sentiment"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# Chat-Antwort generieren
|
| 34 |
+
messages = data.get("history", [])
|
| 35 |
+
messages.append({"role": "user", "content": user_text})
|
| 36 |
+
|
| 37 |
+
# System-Prompt basierend auf Stimmung
|
| 38 |
+
best_sentiment = sorted(sentiment, key=lambda x: x["score"], reverse=True)[0]
|
| 39 |
+
if best_sentiment["label"] == "NEGATIVE" and best_sentiment["score"] > 0.6:
|
| 40 |
+
messages.append({"role": "system", "content": "Der Patient zeigt starke negative Emotionen – schlage Schuldprojektion oder Verdrängung vor."})
|
| 41 |
+
elif best_sentiment["label"] == "POSITIVE" and best_sentiment["score"] > 0.6:
|
| 42 |
+
messages.append({"role": "system", "content": "Der Patient wirkt übertrieben positiv – möglicherweise Abwehrmechanismus durch Kompensation."})
|
| 43 |
+
|
| 44 |
+
# Chat-Antwort generieren
|
| 45 |
+
response = client.chat_completion(
|
| 46 |
+
model="gpt-3.5-turbo",
|
| 47 |
+
messages=messages
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
return {
|
| 51 |
+
"reply": response.generated_text,
|
| 52 |
+
"toneLabel": best_sentiment["label"],
|
| 53 |
+
"toneScore": best_sentiment["score"]
|
| 54 |
+
}
|