apak commited on
Commit
0f9c9bd
·
verified ·
1 Parent(s): a430ce2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -13
app.py CHANGED
@@ -18,26 +18,36 @@ ner_pipe = pipeline("ner", model="xlm-roberta-large-finetuned-conll03-english",
18
  model_id = "Qwen/Qwen2.5-1.5B-Instruct"
19
  tokenizer = AutoTokenizer.from_pretrained(model_id)
20
 
21
- # LLM modelini yükle
22
  llm_model = None
23
  IS_LLM_ENABLED = False
24
 
25
  try:
26
  print("📦 LLM modeli yükleniyor...")
 
 
27
  llm_model = AutoModelForCausalLM.from_pretrained(
28
  model_id,
29
  torch_dtype=torch.float32,
30
- device_map=None,
31
  trust_remote_code=True,
32
  low_cpu_mem_usage=True
33
  )
34
- llm_model = llm_model.to("cpu")
 
35
  llm_model.eval()
 
 
 
 
 
 
36
  IS_LLM_ENABLED = True
37
- print(f"✅ LLM modeli yüklendi!")
38
  except Exception as e:
39
  IS_LLM_ENABLED = False
40
  print(f"⚠️ LLM yüklenemedi: {e}")
 
41
 
42
  # --- 2. WIKIPEDIA API (DOĞRUDAN API KULLANIMI) ---
43
 
@@ -57,6 +67,8 @@ def get_wiki_summary(term):
57
  "Inception": "Inception (film)",
58
  "Oscar": "Akademi Ödülü",
59
  "Nobel": "Nobel Ödülü",
 
 
60
  }
61
 
62
  # Arama terimlerini hazırla
@@ -193,7 +205,6 @@ def test_wikipedia_connection():
193
  logs = []
194
 
195
  try:
196
- # API testi
197
  url = "https://tr.wikipedia.org/w/api.php"
198
  params = {
199
  "action": "query",
@@ -224,7 +235,6 @@ def test_wikipedia_connection():
224
  logs.append(f"⚠️ Sayfa bulunamadı")
225
  except json.JSONDecodeError:
226
  logs.append(f"❌ JSON parse hatası")
227
- logs.append(f"Response: {response.text[:200]}")
228
  else:
229
  logs.append(f"❌ API hatası: {response.status_code}")
230
 
@@ -233,11 +243,11 @@ def test_wikipedia_connection():
233
 
234
  return "\n".join(logs)
235
 
236
- # --- 3. LLM ANALİZ FONKSİYONU ---
237
 
238
  @spaces.GPU
239
  def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label_definitions):
240
- """LLM ile etiket analizi yapar"""
241
  global llm_model, IS_LLM_ENABLED
242
 
243
  if not IS_LLM_ENABLED or llm_model is None:
@@ -246,6 +256,14 @@ def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label
246
  try:
247
  print(f"\n🧠 LLM analizi: '{entity_text}'")
248
 
 
 
 
 
 
 
 
 
249
  # Etiket Tanımları
250
  label_rules = ""
251
  for k, v in custom_label_definitions.items():
@@ -301,22 +319,34 @@ GÜNCEL GÖREV:
301
  Analiz: [4 Adımlı CoT Analizi]
302
  Cevap: [SADECE_ETIKET_ADI]"""
303
 
 
304
  messages = [{"role": "user", "content": prompt}]
305
  text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
306
- model_inputs = tokenizer([text], return_tensors="pt")
 
 
307
  model_inputs = {k: v.to("cpu") for k, v in model_inputs.items()}
308
 
 
 
 
309
  with torch.no_grad():
310
  generated_ids = llm_model.generate(
311
  model_inputs.input_ids,
312
  max_new_tokens=450,
313
  do_sample=False,
314
  temperature=0.1,
315
- pad_token_id=tokenizer.eos_token_id
 
 
316
  )
317
 
318
- response_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
319
- full_output = tokenizer.batch_decode(response_ids, skip_special_tokens=True)[0].strip()
 
 
 
 
320
 
321
  # Etiket Ayıklama
322
  clean_output = full_output.replace("*", "")
@@ -329,11 +359,27 @@ Cevap: [SADECE_ETIKET_ADI]"""
329
  if extracted in valid_keys:
330
  final_label = extracted
331
  print(f"🏷️ Etiket: {final_label}")
 
 
 
 
332
 
333
  return final_label, clean_output
334
 
 
 
 
 
 
 
 
 
 
 
 
335
  except Exception as e:
336
- print(f"❌ LLM hatası: {str(e)}")
 
337
  return "MISC", f"Hata: {str(e)[:100]}"
338
 
339
  # --- 4. ANA İŞLEM HATTI ---
@@ -469,6 +515,7 @@ def check_llm_status():
469
  dtype = next(llm_model.parameters()).dtype
470
  logs.append(f"Device: {device}")
471
  logs.append(f"Dtype: {dtype}")
 
472
  except Exception as e:
473
  logs.append(f"Device kontrol hatası: {str(e)}")
474
  else:
 
18
  model_id = "Qwen/Qwen2.5-1.5B-Instruct"
19
  tokenizer = AutoTokenizer.from_pretrained(model_id)
20
 
21
+ # LLM modelini yükle - RUNTIME ERROR KESİN ÇÖZÜMÜ
22
  llm_model = None
23
  IS_LLM_ENABLED = False
24
 
25
  try:
26
  print("📦 LLM modeli yükleniyor...")
27
+
28
+ # Modeli doğrudan CPU'da yükle
29
  llm_model = AutoModelForCausalLM.from_pretrained(
30
  model_id,
31
  torch_dtype=torch.float32,
32
+ device_map="cpu", # Doğrudan CPU'ya map et
33
  trust_remote_code=True,
34
  low_cpu_mem_usage=True
35
  )
36
+
37
+ # Modeli evaluation moduna al
38
  llm_model.eval()
39
+
40
+ # Device'ı kontrol et
41
+ device = next(llm_model.parameters()).device
42
+ print(f"✅ LLM modeli yüklendi! Device: {device}")
43
+ print(f" Model dtype: {next(llm_model.parameters()).dtype}")
44
+
45
  IS_LLM_ENABLED = True
46
+
47
  except Exception as e:
48
  IS_LLM_ENABLED = False
49
  print(f"⚠️ LLM yüklenemedi: {e}")
50
+ print(traceback.format_exc())
51
 
52
  # --- 2. WIKIPEDIA API (DOĞRUDAN API KULLANIMI) ---
53
 
 
67
  "Inception": "Inception (film)",
68
  "Oscar": "Akademi Ödülü",
69
  "Nobel": "Nobel Ödülü",
70
+ "Amerika": "Amerika",
71
+ "1984": "1984 (roman)",
72
  }
73
 
74
  # Arama terimlerini hazırla
 
205
  logs = []
206
 
207
  try:
 
208
  url = "https://tr.wikipedia.org/w/api.php"
209
  params = {
210
  "action": "query",
 
235
  logs.append(f"⚠️ Sayfa bulunamadı")
236
  except json.JSONDecodeError:
237
  logs.append(f"❌ JSON parse hatası")
 
238
  else:
239
  logs.append(f"❌ API hatası: {response.status_code}")
240
 
 
243
 
244
  return "\n".join(logs)
245
 
246
+ # --- 3. LLM ANALİZ FONKSİYONU (RUNTIME ERROR KESİN ÇÖZÜM) ---
247
 
248
  @spaces.GPU
249
  def refine_label_with_llm(entity_text, full_sentence, wiki_context, custom_label_definitions):
250
+ """LLM ile etiket analizi yapar - RuntimeError kesin çözüm"""
251
  global llm_model, IS_LLM_ENABLED
252
 
253
  if not IS_LLM_ENABLED or llm_model is None:
 
256
  try:
257
  print(f"\n🧠 LLM analizi: '{entity_text}'")
258
 
259
+ # Modelin CPU'da olduğundan emin ol
260
+ try:
261
+ # Modeli CPU'ya taşı (güvenlik için)
262
+ llm_model.to("cpu")
263
+ torch.cuda.empty_cache() if torch.cuda.is_available() else None
264
+ except:
265
+ pass
266
+
267
  # Etiket Tanımları
268
  label_rules = ""
269
  for k, v in custom_label_definitions.items():
 
319
  Analiz: [4 Adımlı CoT Analizi]
320
  Cevap: [SADECE_ETIKET_ADI]"""
321
 
322
+ # Tokenize et
323
  messages = [{"role": "user", "content": prompt}]
324
  text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
325
+
326
+ # Tokenizer'ı CPU'da çalıştır
327
+ model_inputs = tokenizer([text], return_tensors="pt", padding=True, truncation=True)
328
  model_inputs = {k: v.to("cpu") for k, v in model_inputs.items()}
329
 
330
+ print(f"🔄 LLM generate başlatılıyor... (CPU)")
331
+
332
+ # Generate işlemi - CPU'da
333
  with torch.no_grad():
334
  generated_ids = llm_model.generate(
335
  model_inputs.input_ids,
336
  max_new_tokens=450,
337
  do_sample=False,
338
  temperature=0.1,
339
+ pad_token_id=tokenizer.eos_token_id,
340
+ eos_token_id=tokenizer.eos_token_id,
341
+ repetition_penalty=1.1
342
  )
343
 
344
+ # Çıktıyı decode et
345
+ response_ids = generated_ids[0][len(model_inputs.input_ids[0]):]
346
+ full_output = tokenizer.decode(response_ids, skip_special_tokens=True).strip()
347
+
348
+ print(f"✅ LLM çıktısı alındı")
349
+ print(f"📝 Çıktı: {full_output[:100]}...")
350
 
351
  # Etiket Ayıklama
352
  clean_output = full_output.replace("*", "")
 
359
  if extracted in valid_keys:
360
  final_label = extracted
361
  print(f"🏷️ Etiket: {final_label}")
362
+ else:
363
+ print(f"⚠️ Geçersiz etiket: {extracted}")
364
+ else:
365
+ print(f"⚠️ Etiket bulunamadı, MISC atanıyor")
366
 
367
  return final_label, clean_output
368
 
369
+ except RuntimeError as e:
370
+ print(f"❌ RuntimeError: {str(e)}")
371
+ # Modeli resetle
372
+ try:
373
+ llm_model.to("cpu")
374
+ if torch.cuda.is_available():
375
+ torch.cuda.empty_cache()
376
+ except:
377
+ pass
378
+ return "MISC", f"RuntimeError: {str(e)[:100]}"
379
+
380
  except Exception as e:
381
+ print(f"❌ LLM hatası: {type(e).__name__} - {str(e)}")
382
+ print(traceback.format_exc())
383
  return "MISC", f"Hata: {str(e)[:100]}"
384
 
385
  # --- 4. ANA İŞLEM HATTI ---
 
515
  dtype = next(llm_model.parameters()).dtype
516
  logs.append(f"Device: {device}")
517
  logs.append(f"Dtype: {dtype}")
518
+ logs.append(f"CUDA Kullanılabilir: {torch.cuda.is_available()}")
519
  except Exception as e:
520
  logs.append(f"Device kontrol hatası: {str(e)}")
521
  else: