veteroner commited on
Commit
5c1994b
·
verified ·
1 Parent(s): 9af2050

Upload gradio_app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. gradio_app.py +115 -74
gradio_app.py CHANGED
@@ -3,6 +3,8 @@ import torch
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import os
5
  import gc
 
 
6
 
7
  # Spaces import - sadece Hugging Face Spaces'te mevcut
8
  try:
@@ -16,31 +18,57 @@ except ImportError:
16
  spaces = type('spaces', (), {'GPU': spaces_gpu})()
17
 
18
  # ================== Nova AI Modeli ==================
19
- # Sabit model: nova-ai-model Local dosyalardan yüklenir
20
 
21
  # Global değişkenler
22
  model = None
23
  tokenizer = None
24
  model_loaded = False
25
 
26
- def load_model():
27
- """Teknova Nova AI modelini yükle - Memory optimizasyonu ile."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  global model, tokenizer, model_loaded
29
 
30
  if model_loaded:
31
  return "✅ Teknova Nova AI zaten yüklü!"
32
 
 
 
 
 
 
33
  model_path = "nova-ai-model"
34
- print(f"🚀 Nova AI modeli yükleniyor... ({model_path})")
35
 
36
  try:
37
- # Memory temizle
38
- if torch.cuda.is_available():
39
- torch.cuda.empty_cache()
40
- gc.collect()
41
-
42
- # Tokenizer yükle
43
  print("📝 Tokenizer yükleniyor...")
 
 
44
  tokenizer = AutoTokenizer.from_pretrained(
45
  model_path,
46
  trust_remote_code=True,
@@ -48,95 +76,98 @@ def load_model():
48
  local_files_only=True
49
  )
50
 
51
- # Pad token ayarla
52
  if tokenizer.pad_token is None:
53
  tokenizer.pad_token = tokenizer.eos_token
54
 
55
- print("🧠 Model yükleniyor...")
56
- # Model yükle - Memory optimizasyonu
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  model = AutoModelForCausalLM.from_pretrained(
58
  model_path,
59
- torch_dtype=torch.float16,
60
  trust_remote_code=True,
61
  device_map="auto",
62
  low_cpu_mem_usage=True,
63
- local_files_only=True,
64
- load_in_8bit=True # 8-bit quantization için
65
  )
66
 
67
  model_loaded = True
68
- success_msg = f"✅ Teknova Nova AI yüklendi! (Memory Optimized)"
69
- print(success_msg)
70
- return success_msg
71
 
72
  except Exception as e:
73
- error_msg = f"❌ Nova AI model yükleme hatası: {str(e)}"
74
- print(error_msg)
75
- return error_msg
76
 
77
  @spaces.GPU
78
  def chat_with_nova(message, history):
79
- """Teknova Nova AI ile sohbet yanıtı üret - ZeroGPU destekli"""
80
  global model, tokenizer, model_loaded
81
 
82
- # Model yüklü değilse yükle
83
- if not model_loaded:
84
- load_status = load_model()
85
- if "❌" in load_status:
86
- return history + [[message, f"Model yükleme hatası: {load_status}"]]
87
-
88
- if model is None or tokenizer is None:
89
- return history + [[message, "❌ Teknova Nova AI henüz yüklenmedi. Lütfen model yüklenmesini bekleyin..."]]
90
 
91
  if not message.strip():
92
- return history + [[message, "❓ Nova AI'ya mesajınızı yazın."]]
93
 
94
  try:
95
- # Memory temizle
96
- if torch.cuda.is_available():
97
- torch.cuda.empty_cache()
98
-
99
- # Sohbet geçmişini Nova AI formatında hazırla
100
  conversation = ""
101
  if history:
102
- for user_msg, bot_msg in history:
103
  if user_msg and bot_msg:
104
  conversation += f"Kullanıcı: {user_msg}\nNova AI: {bot_msg}\n"
105
 
106
- # Yeni mesajı ekle
107
  conversation += f"Kullanıcı: {message}\nNova AI:"
108
 
109
- # Nova AI Tokenizer ile işle
110
  inputs = tokenizer(
111
- conversation,
112
- return_tensors="pt",
113
- truncation=True,
114
- max_length=1024,
115
  padding=True
116
  )
117
 
118
- # GPU'ya taşı
119
  if torch.cuda.is_available():
120
  inputs = {k: v.to(model.device) for k, v in inputs.items()}
121
 
122
- # Nova AI yanıt üret - Memory optimizasyonu
123
  with torch.no_grad():
124
  outputs = model.generate(
125
  **inputs,
126
- max_new_tokens=256,
127
  temperature=0.7,
128
  top_p=0.9,
129
  do_sample=True,
130
  pad_token_id=tokenizer.pad_token_id,
131
  eos_token_id=tokenizer.eos_token_id,
132
- repetition_penalty=1.1,
133
- no_repeat_ngram_size=2
134
  )
135
 
136
- # Nova AI yanıtını decode et
137
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
138
-
139
- # Sadece Nova AI'ın yeni yanıtını al
140
  new_response = response[len(conversation):].strip()
141
 
142
  # Memory temizle
@@ -147,11 +178,10 @@ def chat_with_nova(message, history):
147
  return history + [[message, new_response]]
148
 
149
  except Exception as e:
150
- return history + [[message, f"❌ Nova AI yanıt üretirken hata: {str(e)}"]]
151
 
152
  # ================== Gradio Arayüzü ==================
153
 
154
- # Gradio arayüzü oluştur
155
  demo = gr.Blocks(
156
  theme=gr.themes.Soft(),
157
  title="Nova AI Chat - Teknova"
@@ -169,24 +199,25 @@ with demo:
169
  <div style="background: linear-gradient(135deg, #ff6b6b, #4ecdc4); color: white; padding: 8px 16px; border-radius: 20px; display: inline-block; font-size: 0.9rem;">
170
  ⚡ Özgün Nova AI Teknolojisi • 🔧 Teknova Innovation • 🚀 ZeroGPU Destekli
171
  </div>
172
- <p style="font-size: 0.9rem; color: #888; margin-top: 10px;">
173
- 🌟 Bu tamamen özgün bir Teknova Nova AI modelidir - Token gerektirmez
174
- </p>
175
  </div>
176
  """)
177
 
178
- # ================== Model Yükleme Butonu ==================
179
  with gr.Row():
180
- load_btn = gr.Button("🔄 Model Yükle", variant="secondary")
181
- status_display = gr.Textbox(
182
- value="Model henüz yüklenmedi. Yüklemek için butona basın.",
183
- label="Model Durumu",
184
- interactive=False
185
- )
186
 
187
- # Chat Interface
 
 
 
 
 
 
 
188
  chatbot = gr.Chatbot(
189
- height=500,
190
  label="Nova AI Sohbet"
191
  )
192
 
@@ -196,22 +227,32 @@ with demo:
196
  )
197
 
198
  with gr.Row():
199
- submit_btn = gr.Button("🚀 Gönder", variant="primary")
200
  clear_btn = gr.Button("🗑️ Temizle")
201
-
202
  gr.HTML("""
203
  <div style="text-align: center; padding: 10px; color: #666;">
204
- <small>💡 Teknova Nova AI ilk yüklenirken biraz bekleyebilir. Memory optimizasyonu ile çalışır.</small>
205
  <br>
206
  <small style="color: #ff6b6b;">🚀 <strong>Teknova Nova AI</strong> - Tamamen özgün model teknolojisi</small>
207
- <br>
208
- <small style="color: #4ecdc4;">🌟 Hugging Face ZeroGPU ile hızlandırılmış!</small>
209
  </div>
210
  """)
211
 
212
- # Event handlers - Basitleştirilmiş
213
- load_btn.click(
214
- fn=load_model,
 
 
 
 
 
 
 
 
 
 
 
 
215
  inputs=None,
216
  outputs=status_display
217
  )
 
3
  from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import os
5
  import gc
6
+ import asyncio
7
+ from pathlib import Path
8
 
9
  # Spaces import - sadece Hugging Face Spaces'te mevcut
10
  try:
 
18
  spaces = type('spaces', (), {'GPU': spaces_gpu})()
19
 
20
  # ================== Nova AI Modeli ==================
 
21
 
22
  # Global değişkenler
23
  model = None
24
  tokenizer = None
25
  model_loaded = False
26
 
27
+ def check_model_files():
28
+ """Model dosyalarının varlığını kontrol et"""
29
+ model_path = "nova-ai-model"
30
+ required_files = [
31
+ "config.json",
32
+ "tokenizer_config.json",
33
+ "generation_config.json"
34
+ ]
35
+
36
+ if not os.path.exists(model_path):
37
+ return f"❌ Model dizini bulunamadı: {model_path}"
38
+
39
+ missing_files = []
40
+ for file in required_files:
41
+ if not os.path.exists(os.path.join(model_path, file)):
42
+ missing_files.append(file)
43
+
44
+ if missing_files:
45
+ return f"❌ Eksik dosyalar: {', '.join(missing_files)}"
46
+
47
+ # Model dosyalarını kontrol et
48
+ model_files = [f for f in os.listdir(model_path) if f.endswith(('.bin', '.safetensors'))]
49
+ if not model_files:
50
+ return "❌ Model dosyaları (.bin/.safetensors) bulunamadı"
51
+
52
+ return f"✅ Model dosyaları hazır: {len(model_files)} dosya bulundu"
53
+
54
+ def load_model_simple():
55
+ """Basit model yükleme - UI'yi bloklamaz"""
56
  global model, tokenizer, model_loaded
57
 
58
  if model_loaded:
59
  return "✅ Teknova Nova AI zaten yüklü!"
60
 
61
+ # Önce dosyaları kontrol et
62
+ file_check = check_model_files()
63
+ if "❌" in file_check:
64
+ return file_check
65
+
66
  model_path = "nova-ai-model"
 
67
 
68
  try:
 
 
 
 
 
 
69
  print("📝 Tokenizer yükleniyor...")
70
+
71
+ # Önce sadece tokenizer yükle (hızlı)
72
  tokenizer = AutoTokenizer.from_pretrained(
73
  model_path,
74
  trust_remote_code=True,
 
76
  local_files_only=True
77
  )
78
 
 
79
  if tokenizer.pad_token is None:
80
  tokenizer.pad_token = tokenizer.eos_token
81
 
82
+ return " Tokenizer yüklendi! Model yüklemek için 'Model Hazırla' butonuna basın."
83
+
84
+ except Exception as e:
85
+ return f"❌ Tokenizer yükleme hatası: {str(e)}"
86
+
87
+ @spaces.GPU
88
+ def load_full_model():
89
+ """Tam model yükleme - ZeroGPU ile"""
90
+ global model, tokenizer, model_loaded
91
+
92
+ if model_loaded:
93
+ return "✅ Teknova Nova AI zaten yüklü!"
94
+
95
+ if tokenizer is None:
96
+ return "❌ Önce tokenizer yüklenmelidir. 'Model Yükle' butonuna basın."
97
+
98
+ model_path = "nova-ai-model"
99
+
100
+ try:
101
+ print("🧠 Model yükleniyor... (Bu işlem 1-2 dakika sürebilir)")
102
+
103
+ # Memory temizle
104
+ if torch.cuda.is_available():
105
+ torch.cuda.empty_cache()
106
+ gc.collect()
107
+
108
+ # Model yükle
109
  model = AutoModelForCausalLM.from_pretrained(
110
  model_path,
111
+ torch_dtype=torch.bfloat16, # bfloat16 daha hızlı
112
  trust_remote_code=True,
113
  device_map="auto",
114
  low_cpu_mem_usage=True,
115
+ local_files_only=True
 
116
  )
117
 
118
  model_loaded = True
119
+ return "✅ Teknova Nova AI tam olarak yüklendi! Artık sohbet edebilirsiniz."
 
 
120
 
121
  except Exception as e:
122
+ return f"❌ Model yükleme hatası: {str(e)}"
 
 
123
 
124
  @spaces.GPU
125
  def chat_with_nova(message, history):
126
+ """Nova AI ile sohbet"""
127
  global model, tokenizer, model_loaded
128
 
129
+ if not model_loaded or model is None:
130
+ return history + [[message, "❌ Model henüz yüklenmedi. Lütfen önce 'Model Hazırla' butonuna basın."]]
 
 
 
 
 
 
131
 
132
  if not message.strip():
133
+ return history + [[message, "❓ Lütfen bir mesaj yazın."]]
134
 
135
  try:
136
+ # Conversation history oluştur
 
 
 
 
137
  conversation = ""
138
  if history:
139
+ for user_msg, bot_msg in history[-3:]: # Son 3 mesajı al
140
  if user_msg and bot_msg:
141
  conversation += f"Kullanıcı: {user_msg}\nNova AI: {bot_msg}\n"
142
 
 
143
  conversation += f"Kullanıcı: {message}\nNova AI:"
144
 
145
+ # Tokenize
146
  inputs = tokenizer(
147
+ conversation,
148
+ return_tensors="pt",
149
+ truncation=True,
150
+ max_length=512, # Daha kısa context
151
  padding=True
152
  )
153
 
 
154
  if torch.cuda.is_available():
155
  inputs = {k: v.to(model.device) for k, v in inputs.items()}
156
 
157
+ # Generate
158
  with torch.no_grad():
159
  outputs = model.generate(
160
  **inputs,
161
+ max_new_tokens=128, # Daha kısa yanıtlar
162
  temperature=0.7,
163
  top_p=0.9,
164
  do_sample=True,
165
  pad_token_id=tokenizer.pad_token_id,
166
  eos_token_id=tokenizer.eos_token_id,
167
+ repetition_penalty=1.1
 
168
  )
169
 
 
170
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
171
  new_response = response[len(conversation):].strip()
172
 
173
  # Memory temizle
 
178
  return history + [[message, new_response]]
179
 
180
  except Exception as e:
181
+ return history + [[message, f"❌ Yanıt üretme hatası: {str(e)}"]]
182
 
183
  # ================== Gradio Arayüzü ==================
184
 
 
185
  demo = gr.Blocks(
186
  theme=gr.themes.Soft(),
187
  title="Nova AI Chat - Teknova"
 
199
  <div style="background: linear-gradient(135deg, #ff6b6b, #4ecdc4); color: white; padding: 8px 16px; border-radius: 20px; display: inline-block; font-size: 0.9rem;">
200
  ⚡ Özgün Nova AI Teknolojisi • 🔧 Teknova Innovation • 🚀 ZeroGPU Destekli
201
  </div>
 
 
 
202
  </div>
203
  """)
204
 
205
+ # Model kontrolleri
206
  with gr.Row():
207
+ check_btn = gr.Button("📁 Dosyaları Kontrol Et", variant="secondary")
208
+ load_tokenizer_btn = gr.Button("🔄 Model Yükle", variant="secondary")
209
+ load_model_btn = gr.Button("🚀 Model Hazırla", variant="primary")
 
 
 
210
 
211
+ status_display = gr.Textbox(
212
+ value="Başlamak için 'Dosyaları Kontrol Et' butonuna basın.",
213
+ label="Model Durumu",
214
+ interactive=False,
215
+ lines=2
216
+ )
217
+
218
+ # Chat interface
219
  chatbot = gr.Chatbot(
220
+ height=400,
221
  label="Nova AI Sohbet"
222
  )
223
 
 
227
  )
228
 
229
  with gr.Row():
230
+ submit_btn = gr.Button("💬 Gönder", variant="primary")
231
  clear_btn = gr.Button("🗑️ Temizle")
232
+
233
  gr.HTML("""
234
  <div style="text-align: center; padding: 10px; color: #666;">
235
+ <small>💡 <strong>Adımlar:</strong> 1️⃣ Dosyaları kontrol et 2️⃣ Model yükle 3️⃣ Model hazırla → 4️⃣ Sohbet et</small>
236
  <br>
237
  <small style="color: #ff6b6b;">🚀 <strong>Teknova Nova AI</strong> - Tamamen özgün model teknolojisi</small>
 
 
238
  </div>
239
  """)
240
 
241
+ # Event handlers
242
+ check_btn.click(
243
+ fn=check_model_files,
244
+ inputs=None,
245
+ outputs=status_display
246
+ )
247
+
248
+ load_tokenizer_btn.click(
249
+ fn=load_model_simple,
250
+ inputs=None,
251
+ outputs=status_display
252
+ )
253
+
254
+ load_model_btn.click(
255
+ fn=load_full_model,
256
  inputs=None,
257
  outputs=status_display
258
  )