apak commited on
Commit
f358f73
·
verified ·
1 Parent(s): 54043dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -135
app.py CHANGED
@@ -6,26 +6,21 @@ import re
6
  import gradio as gr
7
  from transformers import pipeline
8
 
9
- # --- 1. SİSTEM HAZIRLIĞI VE LOGLAMA ---
10
  _initial_logs = []
11
 
12
- # --- 2. XLM-ROBERTA (NER) YÜKLEME ---
13
- # Bu model her zaman CPU'da kalacak şekilde yapılandırıldı.
14
- _initial_logs.append("1. Standart NER Modeli (XLM-Roberta) CPU üzerinde yükleniyor...")
15
  ner_pipe = pipeline(
16
  "ner",
17
  model="xlm-roberta-large-finetuned-conll03-english",
18
  aggregation_strategy="simple",
19
  device="cpu"
20
  )
21
- _initial_logs.append("✅ Standart NER Modeli Hazır.")
22
 
23
- # --- 3. QWEN 2.5 (LLM) YÜKLEME ---
24
- # Başlangıçta sadece RAM'e yüklenir, GPU fonksiyonu çağrıldığında CUDA'ya taşınır.
25
- _initial_logs.append("2. LLM (Qwen 2.5-1.5B) RAM'e yükleniyor...")
26
  model_id = "Qwen/Qwen2.5-1.5B-Instruct"
27
  IS_LLM_ENABLED = False
28
-
29
  try:
30
  gen_pipe = pipeline(
31
  "text-generation",
@@ -35,208 +30,149 @@ try:
35
  trust_remote_code=True
36
  )
37
  IS_LLM_ENABLED = True
38
- _initial_logs.append("✅ LLM (Karar Verici) Başarıyla RAM'e yüklendi.")
39
  except Exception as e:
40
- _initial_logs.append(f"❌ LLM yüklenirken hata oluştu: {e}")
41
- gen_pipe = None
42
 
43
- # --- 4. YARDIMCI FONKSİYONLAR (WIKIPEDIA & GPU) ---
44
 
45
  def get_wiki_summary(term):
 
46
  try:
47
  wikipedia.set_lang("tr")
48
- # auto_suggest=True sayesinde 'Microsoft Windows' yazılsa bile doğru sayfayı bulur
49
- page = wikipedia.page(term, auto_suggest=True, redirect=True)
50
- return page.summary[:600] # İlk 600 karakter LLM için yeterli bağlam sağlar
51
- except wikipedia.exceptions.DisambiguationError as e:
52
- # Eğer çok seçenek çıkarsa ilk seçeneği al
53
- try:
54
- return wikipedia.summary(e.options[0], sentences=2)
55
- except: return None
56
  except:
57
  return None
58
 
59
  @spaces.GPU
60
  def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
61
- """
62
- Paylaştığınız çalışan örnek üzerinden güncellenmiş LLM fonksiyonu.
63
- """
64
  if not IS_LLM_ENABLED or gen_pipe is None:
65
  return "MISC", "LLM aktif değil."
66
 
67
- # ZeroGPU üzerinde modeli GPU'ya taşıma kontrolü
68
  if next(gen_pipe.model.parameters()).device.type != "cuda":
69
  gen_pipe.model.to("cuda")
70
 
71
- label_definitions_str = "\n".join(
72
- [f"- {k}: {v}" for k, v in custom_label_definitions.items()]
73
- )
74
-
75
- # Çalıştığı onaylanmış Few-Shot örnek yapısı
76
- few_shot_examples = """
77
- ÖRNEK 1 (NORP İÇİN):
78
- VARLIK: Türk
79
- BAĞLAM: Türkler, Türkiye Cumhuriyeti'nde yaşayan ve Türkçe konuşan büyük bir etnik gruptur. (NORP tanımı ile eşleşir.)
80
- SONUÇ: NORP
81
-
82
- ÖRNEK 2 (SOFTWARE İÇİN):
83
- VARLIK: Photoshop
84
- BAĞLAM: Adobe tarafından geliştirilen, fotoğraf ve resim düzenleme programı. (SOFTWARE tanımı ile eşleşir.)
85
- SONUÇ: SOFTWARE
86
-
87
- ÖRNEK 3 (PRODUCT İÇİN):
88
- VARLIK: iPhone 15 Pro
89
- BAĞLAM: Apple tarafından üretilen akıllı telefon modelidir. (PRODUCT tanımı ile eşleşir.)
90
- SONUÇ: PRODUCT
91
- """
92
 
 
93
  prompt = f"""Sen uzman bir veri sınıflandırma sistemisin.
94
  Görevin, aşağıdaki BAĞLAM'ı okumak ve ETİKET TANIMLARI'ndan hangisinin varlığa en uygun olduğunu belirlemektir.
95
 
96
- Aşağıdaki adımları izle:
97
- 1. BAĞLAM'ı analiz et.
98
- 2. ETİKET TANIMLARI ile karşılaştır.
99
- 3. BULDUĞUN EŞLEŞMEYİ VE SEÇİMİ TEK SATIRDA ÇIKTI FORMATINA UYGUN OLARAK VER.
100
 
101
- {few_shot_examples}
 
 
 
102
 
103
  ---
104
  ETİKET TANIMLARI:
105
  {label_definitions_str}
106
  ---
107
-
108
- GÖREV VARLIĞI:
109
  VARLIK: {entity_text}
110
  BAĞLAM (Wikipedia): {wiki_context}
111
 
112
  ÇIKTI FORMATI:
113
- Gerekçe: [Tanımlarla eşleşen anahtar kelime veya tanım]
114
- Cevap: [SEÇİLEN ETİKET]
115
 
116
  Gerekçe:"""
117
 
118
  messages = [{"role": "user", "content": prompt}]
119
 
120
  try:
121
- # max_new_tokens değerini kısa tutarak modelin saçmalamasını önlüyoruz
122
- outputs = gen_pipe(messages, max_new_tokens=60, do_sample=False, temperature=0.1)
123
  full_output = outputs[0]["generated_text"][-1]["content"].strip()
124
 
125
- # Paylaştığınız 'Cevap:' satırı bulma mantığı
126
  final_label = "MISC"
127
- reasoning = "Belirlenemedi"
128
 
129
  lines = full_output.split('\n')
130
  for line in lines:
131
  if 'Cevap:' in line:
132
  raw_label = line.split('Cevap:')[-1].strip().upper()
133
- valid_labels = list(custom_label_definitions.keys())
134
- if raw_label in valid_labels:
 
135
  final_label = raw_label
136
- if 'Gerekçe:' in line or not line.startswith('Cevap:'):
137
  reasoning = line.replace('Gerekçe:', '').strip()
138
-
139
  return final_label, reasoning
 
 
140
 
141
- except Exception as e:
142
- return "MISC", f"Hata: {str(e)}"
143
-
144
- # --- 5. ANA İŞLEM HATTI (PIPELINE) ---
145
 
146
  def advanced_ner_pipeline(text, target_labels, progress=gr.Progress()):
147
  log_messages = list(_initial_logs)
148
- log_messages.append(f"🚀 İşlem başladı: '{text[:30]}...'")
149
  yield log_messages, None
150
 
151
- try:
152
- initial_results = ner_pipe(text)
153
- except Exception as e:
154
- log_messages.append(f"❌ NER Hatası: {e}")
155
- yield log_messages, []
156
- return
157
-
158
  final_results = []
159
- total = len(initial_results)
160
 
161
- for i, entity in enumerate(initial_results):
162
  word = entity['word']
163
  label = entity['entity_group']
164
- score = entity['score']
165
 
166
- progress((i + 1) / total, desc=f"İnceleniyor: {word}")
167
 
168
- res_obj = {
169
- "entity": word,
170
- "initial_label": label,
171
- "final_label": label,
172
- "source": "Model",
173
- "reasoning": ""
174
- }
175
-
176
- # Eğer etiket MISC ise RAG sürecini başlat
177
- if label == "MISC" and IS_LLM_ENABLED:
178
- log_messages.append(f"🔍 MISC: '{word}' için Wikipedia taranıyor...")
179
  yield log_messages, None
180
 
181
- wiki_text = get_wiki_summary(word)
182
  if wiki_text:
183
- log_messages.append(f"🤖 LLM (GPU) '{word}' için karar veriyor...")
184
  yield log_messages, None
185
 
186
- new_label, reason = refine_label_with_llm(word, wiki_text, target_labels)
187
- res_obj.update({
188
- "final_label": new_label,
189
- "source": "RAG+LLM",
190
- "reasoning": reason
191
- })
192
- log_messages.append(f"✅ Sonuç: {new_label}")
193
  else:
194
- log_messages.append(f"⚠️ '{word}' için Wikipedia'da bilgi bulunamadı.")
195
- else:
196
- log_messages.append(f"➡️ '{word}' zaten {label} olarak belirlendi.")
197
-
198
  final_results.append(res_obj)
199
- yield log_messages, None
200
-
201
- log_messages.append("✨ Tüm işlemler başarıyla tamamlandı.")
202
- yield log_messages, final_results
203
 
204
- # --- 6. GRADIO ARAYÜZÜ ---
205
 
206
- custom_label_definitions = {
207
  "PER": "Kişi adları.", "ORG": "Kurumlar.", "LOC": "Yerler.",
208
- "DATE": "Tarihler.", "NORP": "Milliyetler/Gruplar.", "BOOK": "Kitaplar.",
209
- "LANGUAGE": "Diller.", "TITLE": "Unvanlar.", "PRODUCT": "Ürünler.",
210
- "SOFTWARE": "Yazılımlar.", "MISC": "Diğer her şey."
211
  }
212
 
213
- def process_ner_request(text, progress=gr.Progress()):
214
- for logs, results in advanced_ner_pipeline(text, custom_label_definitions, progress):
215
- # Logları HTML formatına getir
216
- log_html = "<div style='height:200px; overflow-y:auto; background:#f0f0f0; padding:10px; font-family:monospace;'>"
217
- for m in logs:
218
- log_html += f"<p style='margin:0; border-bottom:1px solid #ddd;'>{m}</p>"
219
- log_html += "</div>"
220
-
221
- # Sonuçları Tablo formatına getir
222
- table_html = "<table style='width:100%; border-collapse:collapse;'><thead><tr style='background:#3b82f6; color:white;'>"
223
- table_html += "<th>Varlık</th><th>İlk Etiket</th><th>Nihai Etiket</th><th>Kaynak</th></tr></thead><tbody>"
224
 
225
- if results:
226
- for r in results:
227
- table_html += f"<tr><td>{r['entity']}</td><td>{r['initial_label']}</td><td><b>{r['final_label']}</b></td><td>{r['source']}</td></tr>"
228
- table_html += "</tbody></table>"
229
 
230
- yield log_html, table_html
231
 
232
  iface = gr.Interface(
233
- fn=process_ner_request,
234
- inputs=gr.Textbox(lines=4, label="Analiz Edilecek Metin"),
235
- outputs=[gr.HTML(label="Sistem Günlüğü"), gr.HTML(label="NER Sonuç Tablosu")],
236
- title="Hibrit NER & RAG Karar Mekanizması",
237
- description="XLM-Roberta (CPU) ile temel NER ve Qwen 2.5 (ZeroGPU) ile akıllı etiket rafine etme."
238
  )
239
 
240
  if __name__ == "__main__":
241
- port = int(os.environ.get('PORT', 7860))
242
- iface.launch(server_name="0.0.0.0", server_port=port)
 
6
  import gradio as gr
7
  from transformers import pipeline
8
 
9
+ # --- 1. MODELLERİN HAZIRLANMASI ---
10
  _initial_logs = []
11
 
12
+ # NER Modeli (Her zaman CPU)
 
 
13
  ner_pipe = pipeline(
14
  "ner",
15
  model="xlm-roberta-large-finetuned-conll03-english",
16
  aggregation_strategy="simple",
17
  device="cpu"
18
  )
19
+ _initial_logs.append("✅ Standart NER Modeli Hazır (CPU).")
20
 
21
+ # LLM Modeli (RAM'e yüklenir, @spaces.GPU ile CUDA'ya geçer)
 
 
22
  model_id = "Qwen/Qwen2.5-1.5B-Instruct"
23
  IS_LLM_ENABLED = False
 
24
  try:
25
  gen_pipe = pipeline(
26
  "text-generation",
 
30
  trust_remote_code=True
31
  )
32
  IS_LLM_ENABLED = True
33
+ _initial_logs.append("✅ LLM (Qwen) CPU belleğine yüklendi.")
34
  except Exception as e:
35
+ _initial_logs.append(f"❌ LLM Yükleme Hatası: {e}")
 
36
 
37
+ # --- 2. YARDIMCI FONKSİYONLAR ---
38
 
39
  def get_wiki_summary(term):
40
+ """Wikipedia'dan en alakalı özeti çeker."""
41
  try:
42
  wikipedia.set_lang("tr")
43
+ # Arama sonuçlarından en üsttekini alarak karmaşayı önler
44
+ search_results = wikipedia.search(term)
45
+ if not search_results:
46
+ return None
47
+ return wikipedia.summary(search_results[0], sentences=2, auto_suggest=False)
 
 
 
48
  except:
49
  return None
50
 
51
  @spaces.GPU
52
  def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
53
+ """Sizin çalışan eski kodunuzdaki formatı kullanan GPU fonksiyonu."""
 
 
54
  if not IS_LLM_ENABLED or gen_pipe is None:
55
  return "MISC", "LLM aktif değil."
56
 
 
57
  if next(gen_pipe.model.parameters()).device.type != "cuda":
58
  gen_pipe.model.to("cuda")
59
 
60
+ label_definitions_str = "\n".join([f"- {k}: {v}" for k, v in custom_label_definitions.items()])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ # Sizin paylaştığınız ve çalışan Few-Shot yapısı
63
  prompt = f"""Sen uzman bir veri sınıflandırma sistemisin.
64
  Görevin, aşağıdaki BAĞLAM'ı okumak ve ETİKET TANIMLARI'ndan hangisinin varlığa en uygun olduğunu belirlemektir.
65
 
66
+ ÖRNEK 1 (NORP İÇİN):
67
+ VARLIK: Türk
68
+ BAĞLAM: Türkler, Türkiye Cumhuriyeti'nde yaşayan büyük bir etnik gruptur.
69
+ SONUÇ: NORP
70
 
71
+ ÖRNEK 2 (SOFTWARE İÇİN):
72
+ VARLIK: Photoshop
73
+ BAĞLAM: Adobe tarafından geliştirilen fotoğraf düzenleme programı.
74
+ SONUÇ: SOFTWARE
75
 
76
  ---
77
  ETİKET TANIMLARI:
78
  {label_definitions_str}
79
  ---
 
 
80
  VARLIK: {entity_text}
81
  BAĞLAM (Wikipedia): {wiki_context}
82
 
83
  ÇIKTI FORMATI:
84
+ Gerekçe: [Analiziniz]
85
+ Cevap: [SADECE ETİKET ADI]
86
 
87
  Gerekçe:"""
88
 
89
  messages = [{"role": "user", "content": prompt}]
90
 
91
  try:
92
+ outputs = gen_pipe(messages, max_new_tokens=80, do_sample=False, temperature=0.1)
 
93
  full_output = outputs[0]["generated_text"][-1]["content"].strip()
94
 
95
+ # Sizin kullandığınız 'Cevap:' satırı yakalama mantığı
96
  final_label = "MISC"
97
+ reasoning = "Bağlam analiz edildi."
98
 
99
  lines = full_output.split('\n')
100
  for line in lines:
101
  if 'Cevap:' in line:
102
  raw_label = line.split('Cevap:')[-1].strip().upper()
103
+ # Gereksiz noktaları veya boşlukları temizle
104
+ raw_label = re.sub(r'[^A-Z_]', '', raw_label)
105
+ if raw_label in custom_label_definitions:
106
  final_label = raw_label
107
+ elif 'Gerekçe:' in line:
108
  reasoning = line.replace('Gerekçe:', '').strip()
109
+
110
  return final_label, reasoning
111
+ except:
112
+ return "MISC", "LLM işleme hatası."
113
 
114
+ # --- 3. ANA İŞLEM HATTI ---
 
 
 
115
 
116
  def advanced_ner_pipeline(text, target_labels, progress=gr.Progress()):
117
  log_messages = list(_initial_logs)
 
118
  yield log_messages, None
119
 
120
+ results = ner_pipe(text)
 
 
 
 
 
 
121
  final_results = []
 
122
 
123
+ for i, entity in enumerate(results):
124
  word = entity['word']
125
  label = entity['entity_group']
 
126
 
127
+ progress((i + 1) / len(results), desc=f"İnceleniyor: {word}")
128
 
129
+ res_obj = {"entity": word, "initial_label": label, "final_label": label, "source": "Model", "reasoning": ""}
130
+
131
+ if label == "MISC":
132
+ standardized_word = word.strip().title()
133
+ log_messages.append(f"⚠️ MISC tespit edildi: '{word}'. Wiki'ye soruluyor...")
 
 
 
 
 
 
134
  yield log_messages, None
135
 
136
+ wiki_text = get_wiki_summary(standardized_word)
137
  if wiki_text:
138
+ log_messages.append(f"🤖 LLM (GPU) '{standardized_word}' için karar veriyor...")
139
  yield log_messages, None
140
 
141
+ new_label, reason = refine_label_with_llm(standardized_word, wiki_text, target_labels)
142
+ res_obj.update({"final_label": new_label, "source": "RAG+LLM", "reasoning": reason})
143
+ log_messages.append(f"🔄 Etiket Güncellendi: {new_label}")
 
 
 
 
144
  else:
145
+ log_messages.append(f"❌ '{word}' için Wiki kaydı yok.")
146
+
 
 
147
  final_results.append(res_obj)
148
+ yield log_messages, final_results
 
 
 
149
 
150
+ # --- 4. ARAYÜZ ---
151
 
152
+ custom_labels = {
153
  "PER": "Kişi adları.", "ORG": "Kurumlar.", "LOC": "Yerler.",
154
+ "NORP": "Milliyetler, etnik veya dini gruplar.", "SOFTWARE": "Yazılımlar, işletim sistemleri.",
155
+ "MOVIE": "Filmler ve sinema eserleri.", "BOOK": "Kitaplar ve yazılı eserler.",
156
+ "PRODUCT": "Ticari ürünler.", "MISC": "Diğer kategoriler."
157
  }
158
 
159
+ def process(text):
160
+ for logs, table in advanced_ner_pipeline(text, custom_labels):
161
+ log_html = "".join([f"<p style='margin:0; font-size:12px;'>{m}</p>" for m in logs])
 
 
 
 
 
 
 
 
162
 
163
+ table_data = []
164
+ if table:
165
+ for r in table:
166
+ table_data.append([r['entity'], r['initial_label'], r['final_label'], r['source']])
167
 
168
+ yield log_html, table_data
169
 
170
  iface = gr.Interface(
171
+ fn=process,
172
+ inputs=gr.Textbox(label="Metin Girin"),
173
+ outputs=[gr.HTML(label="Sistem Günlüğü"), gr.HighlightedText(label="NER Sonuçları") if False else gr.Dataframe(headers=["Varlık", "İlk Etiket", "Nihai Etiket", "Kaynak"])],
174
+ title="NER RAG v2"
 
175
  )
176
 
177
  if __name__ == "__main__":
178
+ iface.launch(server_name="0.0.0.0", server_port=7860)