apak commited on
Commit
c238eff
·
verified ·
1 Parent(s): 4a0642c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -46
app.py CHANGED
@@ -52,38 +52,38 @@ def get_best_wiki_summary(entity):
52
  # -------------------------------
53
  # 3. LLM RAFİNASYON (GPU'da çalışacak - decorator ile)
54
  # -------------------------------
55
- @spaces.GPU(duration=120) # Gerekirse süreyi artır (max ~300 saniye)
56
  def batch_llm_refine(entities_data):
57
  """Birden fazla varlığı tek prompt'ta analiz eder (LLM sadece burada GPU'da yüklenir)"""
58
  if not entities_data:
59
  return {e["entity"]: ("MISC", "Boş veri") for e in entities_data}
60
 
61
- # Modeli sadece burada yükle (GPU mevcut)
62
- MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
63
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
64
- model = AutoModelForCausalLM.from_pretrained(
65
- MODEL_ID,
66
- torch_dtype=torch.bfloat16,
67
- device_map=None, # Manuel taşıyacağız
68
- trust_remote_code=True
69
- )
70
- model.to("cuda") # ZeroGPU'da burada GPU tahsis edilmiş olur
71
-
72
- # Prompt hazırlığı
73
- label_rules = ""
74
- for k, v in CUSTOM_LABELS.items():
75
- label_rules += f"### {k}\n- TANIM: {v['tanim']}\n- ANAHTAR KELİMELER: {', '.join(v['anahtar'])}\n\n"
76
-
77
- tasks = ""
78
- for i, item in enumerate(entities_data, 1):
79
- tasks += f"""
80
  GÖREV {i}:
81
  - VARLIK: {item['entity']}
82
  - CÜMLE: "{item['sentence']}"
83
  - WIKI: "{item['wiki'] or 'Bilgi yok'}"
84
  """
85
 
86
- prompt = f"""Sen bir NER uzmanısın. Aşağıdaki varlıkları sırayla analiz et ve her biri için sadece etiketi ver.
87
  ETİKET KURALLARI:
88
  {label_rules}
89
  FEW-SHOT ÖRNEK:
@@ -96,33 +96,37 @@ VARLIK: iPhone | CÜMLE: Yeni iPhone aldım | WIKI: Apple telefonu → PRODUCT
96
  GÖREV X: [ETIKET]
97
  """
98
 
99
- messages = [{"role": "user", "content": prompt}]
100
- text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
101
- inputs = tokenizer([text], return_tensors="pt").to("cuda")
102
 
103
- with torch.no_grad():
104
- generated = model.generate(
105
- inputs.input_ids,
106
- max_new_tokens=512,
107
- temperature=0.1,
108
- do_sample=False
109
- )
 
 
110
 
111
- response = tokenizer.decode(generated[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
 
 
 
 
 
 
112
 
113
- # Etiketleri çıkar
114
- results = {}
115
- for i, item in enumerate(entities_data, 1):
116
- pattern = rf"GÖREV {i}:\s*([A-Z_]+)"
117
- match = re.search(pattern, response)
118
- label = match.group(1) if match and match.group(1) in CUSTOM_LABELS else "MISC"
119
- results[item["entity"]] = (label, response)
120
 
121
- # Belleği temizle
122
- del model, tokenizer, inputs, generated
123
- torch.cuda.empty_cache()
124
 
125
- return results
 
 
126
 
127
 
128
  # -------------------------------
@@ -149,15 +153,14 @@ def process_ner(text):
149
  logs.append(f"🌐 <b>{word}</b> için Wiki bulundu")
150
  else:
151
  logs.append(f"⚠️ <b>{word}</b> için Wiki bulunamadı")
152
- results.append({"Varlık": word, "İlk": "MISC", "Nihai": "MISC", "Kaynak": "Fallback"})
153
-
154
  misc_entities.append({"entity": word, "sentence": text, "wiki": wiki})
 
155
 
156
  yield "<br>".join(logs), [[r["Varlık"], r["İlk"], f"<b>{r['Nihai']}</b>", r["Kaynak"]] for r in results]
157
 
158
  # LLM rafinasyonu (GPU çağrısı)
159
  if misc_entities:
160
- logs.append("🧠 LLM ile toplu analiz yapılıyor (GPU aktif)...")
161
  yield "<br>".join(logs), [[r["Varlık"], r["İlk"], f"<b>{r['Nihai']}</b>", r["Kaynak"]] for r in results]
162
 
163
  refined = batch_llm_refine(misc_entities)
@@ -170,6 +173,8 @@ def process_ner(text):
170
  r["Nihai"] = new_label
171
  r["Kaynak"] = "RAG+LLM"
172
 
 
 
173
  logs.append("✨ Analiz tamamlandı!")
174
  yield "<br>".join(logs), [[r["Varlık"], r["İlk"], f"<b>{r['Nihai']}</b>", r["Kaynak"]] for r in results]
175
 
 
52
  # -------------------------------
53
  # 3. LLM RAFİNASYON (GPU'da çalışacak - decorator ile)
54
  # -------------------------------
55
+ @spaces.GPU(duration=180) # Süreyi artırdım, model yükleme için yeterli olsun
56
  def batch_llm_refine(entities_data):
57
  """Birden fazla varlığı tek prompt'ta analiz eder (LLM sadece burada GPU'da yüklenir)"""
58
  if not entities_data:
59
  return {e["entity"]: ("MISC", "Boş veri") for e in entities_data}
60
 
61
+ try:
62
+ # Modeli sadece burada yükle (GPU mevcut)
63
+ MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
64
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
65
+ model = AutoModelForCausalLM.from_pretrained(
66
+ MODEL_ID,
67
+ torch_dtype=torch.bfloat16,
68
+ trust_remote_code=True
69
+ )
70
+ model.to("cuda") # ZeroGPU'da burada GPU tahsis edilmiş olur
71
+
72
+ # Prompt hazırlığı
73
+ label_rules = ""
74
+ for k, v in CUSTOM_LABELS.items():
75
+ label_rules += f"### {k}\n- TANIM: {v['tanim']}\n- ANAHTAR KELİMELER: {', '.join(v['anahtar'])}\n\n"
76
+
77
+ tasks = ""
78
+ for i, item in enumerate(entities_data, 1):
79
+ tasks += f"""
80
  GÖREV {i}:
81
  - VARLIK: {item['entity']}
82
  - CÜMLE: "{item['sentence']}"
83
  - WIKI: "{item['wiki'] or 'Bilgi yok'}"
84
  """
85
 
86
+ prompt = f"""Sen bir NER uzmanısın. Aşağıdaki varlıkları sırayla analiz et ve her biri için sadece etiketi ver.
87
  ETİKET KURALLARI:
88
  {label_rules}
89
  FEW-SHOT ÖRNEK:
 
96
  GÖREV X: [ETIKET]
97
  """
98
 
99
+ messages = [{"role": "user", "content": prompt}]
100
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
101
+ inputs = tokenizer([text], return_tensors="pt").to("cuda")
102
 
103
+ with torch.no_grad():
104
+ generated = model.generate(
105
+ inputs.input_ids,
106
+ max_new_tokens=512,
107
+ temperature=0.1,
108
+ do_sample=False
109
+ )
110
+
111
+ response = tokenizer.decode(generated[0][inputs.input_ids.shape[-1]:], skip_special_tokens=True)
112
 
113
+ # Etiketleri çıkar
114
+ results = {}
115
+ for i, item in enumerate(entities_data, 1):
116
+ pattern = rf"GÖREV {i}:\s*([A-Z_]+)"
117
+ match = re.search(pattern, response)
118
+ label = match.group(1) if match and match.group(1) in CUSTOM_LABELS else "MISC"
119
+ results[item["entity"]] = (label, response)
120
 
121
+ # Belleği temizle
122
+ del model, tokenizer, inputs, generated
123
+ torch.cuda.empty_cache()
 
 
 
 
124
 
125
+ return results
 
 
126
 
127
+ except Exception as e:
128
+ print(f"LLM HATASI: {e}")
129
+ return {e["entity"]: ("MISC", f"Hata: {str(e)}") for e in entities_data}
130
 
131
 
132
  # -------------------------------
 
153
  logs.append(f"🌐 <b>{word}</b> için Wiki bulundu")
154
  else:
155
  logs.append(f"⚠️ <b>{word}</b> için Wiki bulunamadı")
 
 
156
  misc_entities.append({"entity": word, "sentence": text, "wiki": wiki})
157
+ results.append({"Varlık": word, "İlk": "MISC", "Nihai": "MISC", "Kaynak": "Fallback"})
158
 
159
  yield "<br>".join(logs), [[r["Varlık"], r["İlk"], f"<b>{r['Nihai']}</b>", r["Kaynak"]] for r in results]
160
 
161
  # LLM rafinasyonu (GPU çağrısı)
162
  if misc_entities:
163
+ logs.append("🧠 LLM ile toplu analiz yapılıyor (GPU tahsis ediliyor)...")
164
  yield "<br>".join(logs), [[r["Varlık"], r["İlk"], f"<b>{r['Nihai']}</b>", r["Kaynak"]] for r in results]
165
 
166
  refined = batch_llm_refine(misc_entities)
 
173
  r["Nihai"] = new_label
174
  r["Kaynak"] = "RAG+LLM"
175
 
176
+ logs.append("✅ LLM analizi tamamlandı")
177
+
178
  logs.append("✨ Analiz tamamlandı!")
179
  yield "<br>".join(logs), [[r["Varlık"], r["İlk"], f"<b>{r['Nihai']}</b>", r["Kaynak"]] for r in results]
180