sherdd commited on
Commit
e1377d6
·
verified ·
1 Parent(s): de69ea8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -0
app.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, TextClassificationPipeline
4
+
5
+ MODEL_ID = os.getenv("MODEL_ID", "cardiffnlp/twitter-xlm-roberta-base-sentiment")
6
+ LABEL_MAP = {0: "negative", 1: "neutral", 2: "positive"} # modelin etiket sirasi
7
+
8
+ # modeli ve tokenizer'i bir kez yukle
9
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
10
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
11
+ pipe = TextClassificationPipeline(model=model, tokenizer=tokenizer, return_all_scores=True, framework="pt", device=-1)
12
+
13
+ def analyze(text: str):
14
+ text = (text or "").strip()
15
+ if not text:
16
+ return {"label": "neutral", "score": 1.0}
17
+ scores = pipe(text)[0] # [{label: "...", score: ...}, ...]
18
+ max_idx = max(range(len(scores)), key=lambda i: scores[i]["score"])
19
+ label = LABEL_MAP.get(max_idx, scores[max_idx]["label"]).lower()
20
+ score = float(scores[max_idx]["score"])
21
+ return {"label": label, "score": round(score, 4)}
22
+
23
+ demo = gr.Interface(
24
+ fn=analyze,
25
+ inputs=gr.Textbox(lines=3, placeholder="type a message..."),
26
+ outputs=gr.JSON(),
27
+ title="chat sentiment api",
28
+ description="returns json: {label: positive|neutral|negative, score: 0..1}",
29
+ )
30
+ demo.api_name = "analyze" # endpoint: /api/predict/analyze
31
+
32
+ if __name__ == "__main__":
33
+ demo.launch()