Lucien10 commited on
Commit
19a7edd
·
verified ·
1 Parent(s): 03e3c15

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+
5
+ HF_TOKEN = os.getenv("HF_TOKEN")
6
+
7
+ API_URL = "https://router.huggingface.co/hf-inference/models/joeddav/xlm-roberta-large-xnli"
8
+
9
+
10
+ def classify(payload):
11
+ try:
12
+ # Gradio JSON input bazen list içinde gelir
13
+ if isinstance(payload, list):
14
+ payload = payload[0]
15
+
16
+ invoice_text = payload.get("invoice_text", "")
17
+ categories = payload.get("categories", [])
18
+
19
+ if not invoice_text or not categories:
20
+ return "NO_INPUT"
21
+
22
+ # Metni kırp ama Türkçe karakterleri bozmadan
23
+ invoice_text = invoice_text.strip()[:3000]
24
+
25
+ candidate_labels = [c["cat_name"].strip() for c in categories]
26
+
27
+ if not candidate_labels:
28
+ return "NO_CATEGORIES"
29
+
30
+ response = requests.post(
31
+ API_URL,
32
+ headers={
33
+ "Authorization": f"Bearer {HF_TOKEN}",
34
+ "Content-Type": "application/json"
35
+ },
36
+ json={
37
+ "inputs": invoice_text,
38
+ "parameters": {
39
+ "candidate_labels": candidate_labels,
40
+ "multi_label": False
41
+ }
42
+ },
43
+ timeout=120
44
+ )
45
+
46
+ print("STATUS:", response.status_code)
47
+ print("RESPONSE:", response.text[:500])
48
+
49
+ if response.status_code != 200:
50
+ return f"HTTP_ERROR_{response.status_code}"
51
+
52
+ result = response.json()
53
+
54
+ # xlm-roberta ve deberta her ikisi de dict döner:
55
+ # {"sequence": "...", "labels": [...], "scores": [...]}
56
+ # Ama HF bazen list of dict döner, ikisini de handle ediyoruz.
57
+
58
+ if isinstance(result, list):
59
+ # list of {"label": ..., "score": ...} formatı
60
+ if not result:
61
+ return "NO_RESULT"
62
+ result.sort(key=lambda x: x.get("score", 0), reverse=True)
63
+ return result[0].get("label", "NO_LABEL")
64
+
65
+ elif isinstance(result, dict):
66
+ labels = result.get("labels", [])
67
+ scores = result.get("scores", [])
68
+
69
+ if not labels:
70
+ return "NO_LABEL"
71
+
72
+ # En yüksek skorlu kategoriyi direkt döndür
73
+ # (random veya penalty yok — model kararına güven)
74
+ best_index = scores.index(max(scores)) if scores else 0
75
+ return labels[best_index]
76
+
77
+ else:
78
+ return "UNEXPECTED_RESPONSE"
79
+
80
+ except requests.exceptions.Timeout:
81
+ return "TIMEOUT"
82
+ except Exception as e:
83
+ import traceback
84
+ traceback.print_exc()
85
+ return f"ERROR: {str(e)}"
86
+
87
+
88
+ gr.Interface(
89
+ fn=classify,
90
+ inputs="json",
91
+ outputs="text"
92
+ ).launch(ssr_mode=False)