apak commited on
Commit
ffccf87
·
verified ·
1 Parent(s): 9d12069

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -98
app.py CHANGED
@@ -1,99 +1,98 @@
1
- import torch
2
- import wikipedia
3
- from transformers import pipeline
4
- import gradio as gr
5
- import os
6
- import re
7
- import spaces # <--- ZeroGPU için gerekli kütüphane
8
-
9
- # --- Global Log Listesini Tanımla ---
10
- _initial_logs = []
11
-
12
- # --- 1. İlk Tarama Modeli (Hızlı NER - CPU'da kalacak) ---
13
- _initial_logs.append("1. Standart NER Modeli CPU üzerinde yükleniyor...")
14
- # NER modelini CPU'ya sabitliyoruz ki GPU kotasından yemesin.
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 (CPU).")
22
-
23
- # --- 2. Akıl Yürütme Modeli (LLM - ZeroGPU için yapılandırma) ---
24
- _initial_logs.append("2. LLM (Qwen) CPU belleğine yükleniyor...")
25
- model_id = "Qwen/Qwen2.5-1.5B-Instruct"
26
- IS_LLM_ENABLED = False
27
-
28
- try:
29
- # Modeli başlangıçta CPU'da (RAM) tutuyoruz.
30
- gen_pipe = pipeline(
31
- "text-generation",
32
- model=model_id,
33
- torch_dtype=torch.bfloat16, # ZeroGPU/H200 için en verimli format
34
- device_map="cpu", # Başlangıçta CPU
35
- trust_remote_code=True
36
- )
37
- IS_LLM_ENABLED = True
38
- _initial_logs.append("✅ LLM (Qwen) Başarıyla RAM'e yüklendi. (Gerektiğinde GPU'ya taşınacak)")
39
-
40
- except Exception as e:
41
- _initial_logs.append(f"❌ LLM yüklenirken kritik hata: {e}")
42
- gen_pipe = None
43
- IS_LLM_ENABLED = False
44
-
45
- # --- LLM ile Etiket Güncelleme Fonksiyonu (GPU Dekoratörü ile) ---
46
- @spaces.GPU # <--- Kritik: GPU sadece bu fonksiyon çağrıldığında tahsis edilir
47
- def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
48
- """LLM kullanarak MISC etiketini rafine eder (ZeroGPU üzerinde çalışır)."""
49
-
50
- if not IS_LLM_ENABLED or gen_pipe is None:
51
- return "MISC", "LLM devre dışı."
52
-
53
- # Modeli bu fonksiyonun içinde GPU'ya taşıyoruz
54
- if gen_pipe.device.type != "cuda":
55
- gen_pipe.model.to("cuda")
56
-
57
- refinable_labels = {k: v for k, v in custom_label_definitions.items() if k not in ["PER", "LOC", "ORG", "MISC"]}
58
- label_definitions_str = "\n".join([f"- {k}: {v}" for k, v in refinable_labels.items()])
59
-
60
- # ... (Buradaki prompt hazırlama kısımları aynı kalıyor, kısalık adına atladım) ...
61
- few_shot_examples = "..." # Mevcut kodundaki örnekleri buraya ekle
62
-
63
- prompt = f"..." # Mevcut kodundaki prompt şablonunu buraya ekle
64
- messages = [{"role": "user", "content": prompt}]
65
-
66
- try:
67
- outputs = gen_pipe(
68
- messages,
69
- max_new_tokens=150,
70
- do_sample=False,
71
- temperature=0.1
72
- )
73
- full_output = outputs[0]["generated_text"][-1]["content"].strip()
74
- except Exception as e:
75
- return "MISC", f"GPU Hatası: {e}"
76
-
77
- # Çıktı işleme mantığın (Regex) aynı kalsın...
78
- final_label = "MISC"
79
- cog_output = ""
80
- valid_labels = list(custom_label_definitions.keys())
81
-
82
- match_cevap = re.search(r'CEVAP:\s*([A-Z_]+)', full_output, re.IGNORECASE)
83
- if match_cevap:
84
- raw_label = match_cevap.group(1).strip().upper()
85
- if raw_label in valid_labels:
86
- final_label = raw_label
87
-
88
- match_reasoning = re.search(r'AKIL YÜRÜTME:\s*(.*)', full_output, re.IGNORECASE | re.DOTALL)
89
- if match_reasoning:
90
- cog_output = match_reasoning.group(1).strip().replace('\n', ' ')
91
-
92
- return final_label, cog_output
93
-
94
- # --- Wikipedia ve Geri Kalan Fonksiyonlar ---
95
- # (get_wiki_summary, advanced_ner_pipeline, process_ner_request fonksiyonları aynen kalabilir)
96
- # Sadece advanced_ner_pipeline içinde refine_label_with_llm'i çağırdığın yer
97
- # artık @spaces.GPU üzerinden otomatik GPU tahsisli çalışacak.
98
-
99
  # ... (Gradio arayüz kodların) ...
 
1
+ import torch
2
+ import wikipedia
3
+ from transformers import pipeline
4
+ import gradio as gr
5
+ import os
6
+ import re
7
+ import spaces # <--- ZeroGPU için gerekli kütüphane
8
+
9
+ # --- Global Log Listesini Tanımla ---
10
+ _initial_logs = []
11
+
12
+ # --- 1. İlk Tarama Modeli (Hızlı NER - CPU'da kalacak) ---
13
+ _initial_logs.append("1. Standart NER Modeli CPU üzerinde yükleniyor...")
14
+ # NER modelini CPU'ya sabitliyoruz ki GPU kotasından yemesin.
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 (CPU).")
22
+
23
+ # --- 2. Akıl Yürütme Modeli (LLM - ZeroGPU için yapılandırma) ---
24
+ _initial_logs.append("2. LLM (Qwen) CPU belleğine yükleniyor...")
25
+ model_id = "Qwen/Qwen2.5-1.5B-Instruct"
26
+ IS_LLM_ENABLED = False
27
+
28
+ try:
29
+ # Modeli başlangıçta CPU'da (RAM) tutuyoruz.
30
+ gen_pipe = pipeline(
31
+ "text-generation",
32
+ model=model_id,
33
+ model_kwargs={"dtype": torch.bfloat16}, # torch_dtype yerine dtype
34
+ device_map="cpu",
35
+ trust_remote_code=True
36
+ )
37
+ IS_LLM_ENABLED = True
38
+ print("✅ LLM (Qwen) Başarıyla RAM'e yüklendi!") # Loglarda bunu görmeliyiz
39
+
40
+ except Exception as e:
41
+ _initial_logs.append(f"❌ LLM yüklenirken kritik hata: {e}")
42
+
43
+
44
+ # --- LLM ile Etiket Güncelleme Fonksiyonu (GPU Dekoratörü ile) ---
45
+ @spaces.GPU # <--- Kritik: GPU sadece bu fonksiyon çağrıldığında tahsis edilir
46
+ def refine_label_with_llm(entity_text, wiki_context, custom_label_definitions):
47
+ """LLM kullanarak MISC etiketini rafine eder (ZeroGPU üzerinde çalışır)."""
48
+
49
+ if not IS_LLM_ENABLED or gen_pipe is None:
50
+ return "MISC", "LLM devre dışı."
51
+
52
+ # Modeli bu fonksiyonun içinde GPU'ya taşıyoruz
53
+ if gen_pipe.device.type != "cuda":
54
+ gen_pipe.model.to("cuda")
55
+
56
+ refinable_labels = {k: v for k, v in custom_label_definitions.items() if k not in ["PER", "LOC", "ORG", "MISC"]}
57
+ label_definitions_str = "\n".join([f"- {k}: {v}" for k, v in refinable_labels.items()])
58
+
59
+ # ... (Buradaki prompt hazırlama kısımları aynı kalıyor, kısalık adına atladım) ...
60
+ few_shot_examples = "..." # Mevcut kodundaki örnekleri buraya ekle
61
+
62
+ prompt = f"..." # Mevcut kodundaki prompt şablonunu buraya ekle
63
+ messages = [{"role": "user", "content": prompt}]
64
+
65
+ try:
66
+ outputs = gen_pipe(
67
+ messages,
68
+ max_new_tokens=150,
69
+ do_sample=False,
70
+ temperature=0.1
71
+ )
72
+ full_output = outputs[0]["generated_text"][-1]["content"].strip()
73
+ except Exception as e:
74
+ return "MISC", f"GPU Hatası: {e}"
75
+
76
+ # Çıktı işleme mantığın (Regex) aynı kalsın...
77
+ final_label = "MISC"
78
+ cog_output = ""
79
+ valid_labels = list(custom_label_definitions.keys())
80
+
81
+ match_cevap = re.search(r'CEVAP:\s*([A-Z_]+)', full_output, re.IGNORECASE)
82
+ if match_cevap:
83
+ raw_label = match_cevap.group(1).strip().upper()
84
+ if raw_label in valid_labels:
85
+ final_label = raw_label
86
+
87
+ match_reasoning = re.search(r'AKIL YÜRÜTME:\s*(.*)', full_output, re.IGNORECASE | re.DOTALL)
88
+ if match_reasoning:
89
+ cog_output = match_reasoning.group(1).strip().replace('\n', ' ')
90
+
91
+ return final_label, cog_output
92
+
93
+ # --- Wikipedia ve Geri Kalan Fonksiyonlar ---
94
+ # (get_wiki_summary, advanced_ner_pipeline, process_ner_request fonksiyonları aynen kalabilir)
95
+ # Sadece advanced_ner_pipeline içinde refine_label_with_llm'i çağırdığın yer
96
+ # artık @spaces.GPU üzerinden otomatik GPU tahsisli çalışacak.
97
+
 
98
  # ... (Gradio arayüz kodların) ...