Upload 5 files
Browse filesFiles changed (5)
- LICENSEAdded+22
- README.md+19-7
- app.pyAdded+136
- requirements.txtAdded+7
- train.pyAdded+47
12345678910111213141516171819202122
MIT License
Copyright (c)
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910111213---title: F2emoji: 💻colorFrom: bluecolorTo: yellowsdk: gradiosdk_version: 6.3.0app_file: app.pypinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425---title: Verhaltens-Prädiktor (Text)emoji: 🧠colorFrom: indigocolorTo: bluesdk: gradiosdk_version: 4.37.0python_version: 3.10app_file: app.pylicense: mit---# 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`**Optionales Feintuning**- Datensatz: `dair-ai/emotion`Hinweis: Ergebnisse sind probabilistisch und können Verzerrungen enthalten. Kein diagnostisches Tool.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
import os, jsonfrom typing import Dict, Listimport gradio as grimport torchfrom 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()1234567
transformers>=4.44.0accelerate>=0.33.0torchgradio>=4.37.0datasets>=2.20.0scikit-learn>=1.3.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647
import os, numpy as np, evaluatefrom dataclasses import dataclassfrom datasets import load_datasetfrom transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
MODEL_NAME = os.getenv("BASE_MODEL", "distilroberta-base")OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./emotion-finetuned")
@dataclassclass Cfg: dataset: str = "dair-ai/emotion" text_col: str = "text" label_col: str = "label"
cfg = Cfg()ds = load_dataset(cfg.dataset)labels = ds["train"].features[cfg.label_col].namesnum_labels = len(labels)
tok = AutoTokenizer.from_pretrained(MODEL_NAME)def tokenize(b): return tok(b[cfg.text_col], padding=True, truncation=True)ds_tok = ds.map(tokenize, batched=True)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=num_labels)metric = evaluate.load("accuracy")def compute_metrics(pred): logits, y_true = pred y_pred = np.argmax(logits, axis=-1) return metric.compute(predictions=y_pred, references=y_true)
args = TrainingArguments( OUTPUT_DIR, learning_rate=2e-5, per_device_train_batch_size=16, per_device_eval_batch_size=16, num_train_epochs=1, evaluation_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, report_to=[])
trainer = Trainer(model=model, args=args, train_dataset=ds_tok["train"], eval_dataset=ds_tok["validation"], tokenizer=tok, compute_metrics=compute_metrics)
if __name__ == "__main__": trainer.train() trainer.save_model(OUTPUT_DIR) tok.save_pretrained(OUTPUT_DIR)LICENSEAdded+22
README.md+19-7
app.pyAdded+136
requirements.txtAdded+7
train.pyAdded+47