Download app.py from Etk02/f3: direct link, hf CLI and curl.
- Browser
- Download file 5.02 kB
-
https://huggingface.co/spaces/Etk02/f3/resolve/main/app.py
- Command line
-
hf download hf://spaces/Etk02/f3/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Etk02/f3/resolve/main/app.py
5.02 kB
| import os, json | |
| from typing import Dict, List | |
| import gradio as gr | |
| import torch | |
| from transformers import pipeline | |
| # Modelle (können über Space-Umgebungsvariablen überschrieben werden) | |
| 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 | |
| # Deutsche Label-Sets | |
| SOCIAL_LABELS = [ | |
| "unterstützend", | |
| "empathisch", | |
| "kooperativ", | |
| "konflikthaft", | |
| "dominant/direktiv", | |
| "neutral" | |
| ] | |
| DECISION_LABELS = ["risikosuchend", "risikoscheu", "impulsiv", "überlegt"] | |
| SITUATION_LABELS = ["positive Reaktion", "negative Reaktion", "Stressreaktion", "Vermeidung"] | |
| # Lazy init | |
| _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() | |