Spaces:
Build error

File size: 4,681 Bytes
f5ece45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 = [
    "supportive", "empathic", "cooperative", "conflict", "dominant/directive", "neutral"
]
DECISION_LABELS = ["risk-seeking", "risk-averse", "impulsive", "deliberative"]
SITUATION_LABELS = ["positive reaction", "negative reaction", "stress reaction", "avoidance"]

_emotion_pipe = None
_zsc_pipe = None

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 _normalize(items: List[Dict[str, float]]):
    s = sum(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 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,
        "social_interaction": social_table[0][0] if social_table else "",
        "decision_style":     decision_table[0][0] if decision_table else "",
        "situation_reaction": 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 = 5):
    templates = [
        ("I can't take this anymore. My hands are shaking.", "stress reaction"),
        ("Let's take the chance – we might fail, but it will be worth it!", "risk-seeking"),
        ("I'm really proud of you. How can I help?", "supportive"),
        ("Back off. Do it my way or not at all.", "dominant/directive"),
        ("I feel so happy today – everything seems possible!", "positive reaction"),
    ]
    out = []
    for i in range(n):
        t, tag = templates[i % len(templates)]
        out.append({"text": t, "hint": tag})
    return json.dumps(out, ensure_ascii=False, indent=2)

with gr.Blocks(title="Behavior Predictor (Text)") as demo:
    gr.Markdown("""
# Behavior Predictor (Text)
Vorhersage von **Emotion**, **sozialem Interaktionsstil**, **Entscheidungsstil** und **Situationsreaktion** aus freiem Text.
**Modelle**: `j-hartmann/emotion-english-distilroberta-base` (Emotion), `facebook/bart-large-mnli` (Zero-Shot)
Hinweis: Probabilistisch. Kein diagnostisches Tool.
""")
    with gr.Row():
        inp = gr.Textbox(label="Eingabetext", placeholder="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(5), outputs=summary)

if __name__ == "__main__":
    demo.launch()