File size: 4,953 Bytes
b3453b9 | 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 |
import os, json
from typing import Dict, List
import gradio as gr
import torch
from transformers import pipeline
EMOTION_MODEL = os.getenv("EMOTION_MODEL", "j-hartmann/emotion-english-distilroberta-base")
ZSC_MODEL = os.getenv("ZSC_MODEL", "facebook/bart-large-mnli")
DEVICE = 0 if torch.cuda.is_available() else -1
SOCIAL_LABELS = [
"unterstützend",
"empathisch",
"kooperativ",
"konflikthaft",
"dominant/direktiv",
"neutral"
]
DECISION_LABELS = [
"risikosuchend",
"risikoscheu",
"impulsiv",
"überlegt"
]
SITUATION_LABELS = [
"positive Reaktion",
"negative Reaktion",
"Stressreaktion",
"Vermeidung"
]
_emotion_pipe = None
_zsc_pipe = None
def _normalize(items: List[Dict[str, float]]):
s = sum(float(x["score"]) for x in items) or 1.0
for x in items:
x["score"] = round(float(x["score"]) / s, 6)
return items
def _table(items: List[Dict[str, float]]):
return [[x["label"], round(100*float(x["score"]), 2)] for x in items]
def get_emotion_pipe():
global _emotion_pipe
if _emotion_pipe is None:
_emotion_pipe = pipeline(
"text-classification",
model=EMOTION_MODEL,
device=DEVICE,
return_all_scores=True,
top_k=None,
)
return _emotion_pipe
def get_zsc_pipe():
global _zsc_pipe
if _zsc_pipe is None:
_zsc_pipe = pipeline("zero-shot-classification", model=ZSC_MODEL, device=DEVICE)
return _zsc_pipe
def predict_emotion(text: str):
raw = get_emotion_pipe()(text)[0]
norm = _normalize(raw)
norm_sorted = sorted(norm, key=lambda x: x["score"], reverse=True)
top = norm_sorted[0]["label"] if norm_sorted else "unknown"
return top, _table(norm_sorted)
def zsc(text: str, labels: List[str]):
out = get_zsc_pipe()(text, candidate_labels=labels, multi_label=True)
items = [{"label": l, "score": float(s)} for l, s in zip(out["labels"], out["scores"])]
norm = _normalize(items)
return _table(sorted(norm, key=lambda x: x[1], reverse=True))
def predict_all(text: str):
if not text or not text.strip():
return gr.update(value=""), [], [], [], []
emo_label, emo_table = predict_emotion(text)
social_table = zsc(text, SOCIAL_LABELS)
decision_table = zsc(text, DECISION_LABELS)
situation_table = zsc(text, SITUATION_LABELS)
summary = {
"emotion": emo_label,
"sozialer_Interaktionsstil": social_table[0][0] if social_table else "",
"Entscheidungsstil": decision_table[0][0] if decision_table else "",
"Situationsreaktion": situation_table[0][0] if situation_table else "",
}
return json.dumps(summary, ensure_ascii=False, indent=2), emo_table, social_table, decision_table, situation_table
def generate_synthetic(n: int = 6):
templates = [
("Ich bin so stolz auf dich. Wie kann ich dich unterstützen?", "unterstützend"),
("Bitte halte dich an meinen Plan. So wird es gemacht.", "dominant/direktiv"),
("Können wir eine Lösung finden, die für alle passt?", "kooperativ"),
("Lass uns das Risiko eingehen – es könnte sich lohnen!", "risikosuchend"),
("Mir ist unwohl, ich möchte das lieber vermeiden.", "Vermeidung"),
("Meine Hände zittern, mir wird alles zu viel.", "Stressreaktion"),
]
out = []
for i in range(n):
t, tag = templates[i % len(templates)]
out.append({"text": t, "Hinweis": tag})
return json.dumps(out, ensure_ascii=False, indent=2)
with gr.Blocks(title="Verhaltens-Prädiktor (Text)") as demo:
gr.Markdown("""
# Verhaltens-Prädiktor (Text)
Vorhersage von **Emotion**, **sozialem Interaktionsstil**, **Entscheidungsstil** und **Situationsreaktion** aus freiem Text.
**Modelle**
- Emotion: `j-hartmann/emotion-english-distilroberta-base`
- Zero‑Shot: `facebook/bart-large-mnli`
Hinweis: Ergebnisse sind probabilistisch und können Verzerrungen enthalten. Kein diagnostisches Tool.
""")
with gr.Row():
inp = gr.Textbox(label="Eingabetext", placeholder="Schreibe hier einen Satz oder Absatz…", lines=4)
with gr.Column():
btn = gr.Button("Vorhersagen", variant="primary")
gen = gr.Button("Beispieltexte erzeugen")
summary = gr.JSON(label="Zusammenfassung")
with gr.Row():
emo = gr.Dataframe(headers=["Label", "Score %"], label="Emotion (Scores)")
social = gr.Dataframe(headers=["Label", "Score %"], label="Soziale Interaktion (Scores)")
with gr.Row():
decision = gr.Dataframe(headers=["Label", "Score %"], label="Entscheidungsstil (Scores)")
situation = gr.Dataframe(headers=["Label", "Score %"], label="Situationsreaktion (Scores)")
btn.click(predict_all, inputs=inp, outputs=[summary, emo, social, decision, situation])
gen.click(lambda: generate_synthetic(6), outputs=summary)
if __name__ == "__main__":
demo.launch()
|