veteroner commited on
Commit
2b776ad
·
verified ·
1 Parent(s): 805fa80

Upload gradio_app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. gradio_app.py +256 -218
gradio_app.py CHANGED
@@ -1,219 +1,257 @@
1
- import gradio as gr
2
- import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer
4
- import os
5
-
6
- # Spaces import - sadece Hugging Face Spaces'te mevcut
7
- try:
8
- import spaces
9
- HAS_SPACES = True
10
- except ImportError:
11
- HAS_SPACES = False
12
- # Spaces decorator'ı için dummy fonksiyon
13
- def spaces_gpu(func):
14
- return func
15
- spaces = type('spaces', (), {'GPU': spaces_gpu})()
16
-
17
- # ================== Nova AI Modeli ==================
18
- # Sabit model: veteroner/NovaAI Hub'dan yüklenir
19
-
20
- # Global değişkenler
21
- model = None
22
- tokenizer = None
23
-
24
- @spaces.GPU
25
- def load_model():
26
- """Teknova Nova AI modelini yükle - ZeroGPU destekli."""
27
- global model, tokenizer
28
-
29
- model_path = "nova-ai-model"
30
- print(f"🚀 Nova AI modeli yükleniyor... ({model_path})")
31
-
32
- try:
33
- # Tokenizer yükle
34
- tokenizer = AutoTokenizer.from_pretrained(
35
- model_path,
36
- trust_remote_code=True,
37
- use_fast=True
38
- )
39
-
40
- # Pad token ayarla
41
- if tokenizer.pad_token is None:
42
- tokenizer.pad_token = tokenizer.eos_token
43
-
44
- # Model yükle - ZeroGPU optimizasyonu
45
- model = AutoModelForCausalLM.from_pretrained(
46
- model_path,
47
- torch_dtype=torch.float16,
48
- trust_remote_code=True,
49
- device_map="auto",
50
- low_cpu_mem_usage=True
51
- )
52
-
53
- success_msg = f"✅ Teknova Nova AI yüklendi! (Local + ZeroGPU)"
54
- print(success_msg)
55
- return success_msg
56
-
57
- except Exception as e:
58
- error_msg = f"❌ Nova AI model yükleme hatası: {str(e)}"
59
- print(error_msg)
60
- return error_msg
61
-
62
- @spaces.GPU
63
- def chat_response(message, history):
64
- """Teknova Nova AI ile sohbet yanıtı üret - ZeroGPU destekli"""
65
- global model, tokenizer
66
-
67
- if model is None or tokenizer is None:
68
- return " Teknova Nova AI henüz yüklenmedi. Lütfen model yüklenmesini bekleyin..."
69
-
70
- if not message.strip():
71
- return "❓ Nova AI'ya mesajınızı yazın."
72
-
73
- try:
74
- # Sohbet geçmişini Nova AI formatında hazırla
75
- conversation = ""
76
- for user_msg, bot_msg in history:
77
- conversation += f"Kullanıcı: {user_msg}\nNova AI: {bot_msg}\n"
78
-
79
- # Yeni mesajı ekle
80
- conversation += f"Kullanıcı: {message}\nNova AI:"
81
-
82
- # Nova AI Tokenizer ile işle
83
- inputs = tokenizer(
84
- conversation,
85
- return_tensors="pt",
86
- truncation=True,
87
- max_length=2048,
88
- padding=True
89
- )
90
-
91
- # GPU'ya taşı
92
- if torch.cuda.is_available():
93
- inputs = {k: v.to(model.device) for k, v in inputs.items()}
94
-
95
- # Nova AI yanıt üret - ZeroGPU optimizasyonu
96
- with torch.no_grad():
97
- outputs = model.generate(
98
- **inputs,
99
- max_new_tokens=512,
100
- temperature=0.7,
101
- top_p=0.9,
102
- do_sample=True,
103
- pad_token_id=tokenizer.pad_token_id,
104
- eos_token_id=tokenizer.eos_token_id,
105
- repetition_penalty=1.1
106
- )
107
-
108
- # Nova AI yanıtını decode et
109
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
110
-
111
- # Sadece Nova AI'ın yeni yanıtını al
112
- new_response = response[len(conversation):].strip()
113
-
114
- return new_response
115
-
116
- except Exception as e:
117
- return f"❌ Nova AI yanıt üretirken hata: {str(e)}"
118
-
119
- # Başlangıçta modeli yükle
120
- initial_status = load_model()
121
-
122
- # Gradio arayüzü oluştur
123
- with gr.Blocks(
124
- theme=gr.themes.Soft(),
125
- title="Nova AI Chat - Teknova",
126
- css="""
127
- .gradio-container {
128
- max-width: 800px;
129
- margin: 0 auto;
130
- }
131
- .chat-message {
132
- border-radius: 10px;
133
- padding: 10px;
134
- margin: 5px 0;
135
- }
136
- """
137
- ) as demo:
138
-
139
- gr.HTML("""
140
- <div style="text-align: center; padding: 20px;">
141
- <h1 style="background: linear-gradient(135deg, #ff6b6b, #4ecdc4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5rem; font-weight: bold;">
142
- 🚀 Teknova Nova AI
143
- </h1>
144
- <p style="font-size: 1.2rem; color: #666; margin: 10px 0;">
145
- <strong>Teknova</strong> tarafından geliştirilen <strong>özgün</strong> yapay zeka modeli
146
- </p>
147
- <div style="background: linear-gradient(135deg, #ff6b6b, #4ecdc4); color: white; padding: 8px 16px; border-radius: 20px; display: inline-block; font-size: 0.9rem;">
148
- Özgün Nova AI Teknolojisi �� Teknova Innovation • 🚀 ZeroGPU Destekli
149
- </div>
150
- <p style="font-size: 0.9rem; color: #888; margin-top: 10px;">
151
- 🌟 Bu tamamen özgün bir Teknova Nova AI modelidir - Token gerektirmez
152
- </p>
153
- </div>
154
- """)
155
-
156
- # ================== Model Durumu ==================
157
- with gr.Row():
158
- statusbox = gr.Textbox(
159
- value=initial_status,
160
- label="Model Durumu",
161
- interactive=False
162
- )
163
-
164
- chatbot = gr.Chatbot(
165
- height=500,
166
- show_label=False,
167
- show_share_button=False,
168
- show_copy_button=True,
169
- avatar_images=[
170
- None, # User avatar
171
- "🤖" # Bot avatar
172
- ],
173
- type="messages"
174
- )
175
-
176
- with gr.Row():
177
- msg = gr.Textbox(
178
- placeholder="Nova AI'ya mesajınızı yazın...",
179
- show_label=False,
180
- scale=4
181
- )
182
- submit = gr.Button("🚀 Gönder", scale=1, variant="primary")
183
-
184
- with gr.Row():
185
- clear = gr.Button("🗑️ Temizle", scale=1)
186
-
187
- gr.HTML("""
188
- <div style="text-align: center; padding: 10px; color: #666;">
189
- <small>💡 Teknova Nova AI ilk yüklenirken biraz bekleyebilir. Özgün AI teknolojisi ile güçlendirilmiştir.</small>
190
- <br>
191
- <small style="color: #ff6b6b;">🚀 <strong>Teknova Nova AI</strong> - Tamamen özgün model teknolojisi</small>
192
- <br>
193
- <small style="color: #4ecdc4;">🌟 Hugging Face ZeroGPU ile hızlandırılmış!</small>
194
- </div>
195
- """)
196
-
197
- # Event handlers
198
- def user_message(message, history):
199
- return "", history + [[message, None]]
200
-
201
- def bot_message(history):
202
- user_message = history[-1][0]
203
- bot_response = chat_response(user_message, history[:-1])
204
- history[-1][1] = bot_response
205
- return history
206
-
207
- msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
208
- bot_message, chatbot, chatbot
209
- )
210
- submit.click(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
211
- bot_message, chatbot, chatbot
212
- )
213
- clear.click(lambda: None, None, chatbot, queue=False)
214
-
215
- if __name__ == "__main__":
216
- demo.launch(
217
- server_name="0.0.0.0",
218
- share=True # port otomatik bulunur, 0.0.0.0 + ilk boş port
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  )
 
1
+ import gradio as gr
2
+ 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:
9
+ import spaces
10
+ HAS_SPACES = True
11
+ except ImportError:
12
+ HAS_SPACES = False
13
+ # Spaces decorator'ı için dummy fonksiyon
14
+ def spaces_gpu(func):
15
+ return func
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,
47
+ use_fast=True,
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_response(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 f"Model yükleme hatası: {load_status}"
87
+
88
+ if model is None or tokenizer is None:
89
+ return "❌ Teknova Nova AI henüz yüklenmedi. Lütfen model yüklenmesini bekleyin..."
90
+
91
+ if not message.strip():
92
+ return "❓ 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
+ for user_msg, bot_msg in history:
102
+ conversation += f"Kullanıcı: {user_msg}\nNova AI: {bot_msg}\n"
103
+
104
+ # Yeni mesajı ekle
105
+ conversation += f"Kullanıcı: {message}\nNova AI:"
106
+
107
+ # Nova AI Tokenizer ile işle
108
+ inputs = tokenizer(
109
+ conversation,
110
+ return_tensors="pt",
111
+ truncation=True,
112
+ max_length=1024, # Kısaltıldı
113
+ padding=True
114
+ )
115
+
116
+ # GPU'ya taşı
117
+ if torch.cuda.is_available():
118
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
119
+
120
+ # Nova AI yanıt üret - Memory optimizasyonu
121
+ with torch.no_grad():
122
+ outputs = model.generate(
123
+ **inputs,
124
+ max_new_tokens=256, # Kısaltıldı
125
+ temperature=0.7,
126
+ top_p=0.9,
127
+ do_sample=True,
128
+ pad_token_id=tokenizer.pad_token_id,
129
+ eos_token_id=tokenizer.eos_token_id,
130
+ repetition_penalty=1.1,
131
+ no_repeat_ngram_size=2
132
+ )
133
+
134
+ # Nova AI yanıtını decode et
135
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
136
+
137
+ # Sadece Nova AI'ın yeni yanıtını al
138
+ new_response = response[len(conversation):].strip()
139
+
140
+ # Memory temizle
141
+ del outputs
142
+ if torch.cuda.is_available():
143
+ torch.cuda.empty_cache()
144
+
145
+ return new_response
146
+
147
+ except Exception as e:
148
+ return f"❌ Nova AI yanıt üretirken hata: {str(e)}"
149
+
150
+ # ================== Gradio Arayüzü ==================
151
+
152
+ # Gradio arayüzü oluştur
153
+ with gr.Blocks(
154
+ theme=gr.themes.Soft(),
155
+ title="Nova AI Chat - Teknova",
156
+ css="""
157
+ .gradio-container {
158
+ max-width: 800px;
159
+ margin: 0 auto;
160
+ }
161
+ .chat-message {
162
+ border-radius: 10px;
163
+ padding: 10px;
164
+ margin: 5px 0;
165
+ }
166
+ """
167
+ ) as demo:
168
+
169
+ gr.HTML("""
170
+ <div style="text-align: center; padding: 20px;">
171
+ <h1 style="background: linear-gradient(135deg, #ff6b6b, #4ecdc4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5rem; font-weight: bold;">
172
+ 🚀 Teknova Nova AI
173
+ </h1>
174
+ <p style="font-size: 1.2rem; color: #666; margin: 10px 0;">
175
+ <strong>Teknova</strong> tarafından geliştirilen <strong>özgün</strong> yapay zeka modeli
176
+ </p>
177
+ <div style="background: linear-gradient(135deg, #ff6b6b, #4ecdc4); color: white; padding: 8px 16px; border-radius: 20px; display: inline-block; font-size: 0.9rem;">
178
+ ⚡ Özgün Nova AI Teknolojisi • 🔧 Teknova Innovation • 🚀 ZeroGPU Destekli
179
+ </div>
180
+ <p style="font-size: 0.9rem; color: #888; margin-top: 10px;">
181
+ 🌟 Bu tamamen özgün bir Teknova Nova AI modelidir - Token gerektirmez
182
+ </p>
183
+ </div>
184
+ """)
185
+
186
+ # ================== Model Yükleme Butonu ==================
187
+ with gr.Row():
188
+ load_btn = gr.Button("🔄 Model Yükle", variant="secondary")
189
+ status_display = gr.Textbox(
190
+ value="Model henüz yüklenmedi. Yüklemek için butona basın.",
191
+ label="Model Durumu",
192
+ interactive=False
193
+ )
194
+
195
+ chatbot = gr.Chatbot(
196
+ height=500,
197
+ show_label=False,
198
+ show_share_button=False,
199
+ show_copy_button=True,
200
+ avatar_images=[
201
+ None, # User avatar
202
+ "🤖" # Bot avatar
203
+ ],
204
+ type="messages"
205
+ )
206
+
207
+ with gr.Row():
208
+ msg = gr.Textbox(
209
+ placeholder="Nova AI'ya mesajınızı yazın...",
210
+ show_label=False,
211
+ scale=4
212
+ )
213
+ submit = gr.Button("🚀 Gönder", scale=1, variant="primary")
214
+
215
+ with gr.Row():
216
+ clear = gr.Button("🗑️ Temizle", scale=1)
217
+
218
+ gr.HTML("""
219
+ <div style="text-align: center; padding: 10px; color: #666;">
220
+ <small>💡 Teknova Nova AI ilk yüklenirken biraz bekleyebilir. Memory optimizasyonu ile çalışır.</small>
221
+ <br>
222
+ <small style="color: #ff6b6b;">🚀 <strong>Teknova Nova AI</strong> - Tamamen özgün model teknolojisi</small>
223
+ <br>
224
+ <small style="color: #4ecdc4;">🌟 Hugging Face ZeroGPU ile hızlandırılmış!</small>
225
+ </div>
226
+ """)
227
+
228
+ # Event handlers
229
+ def user_message(message, history):
230
+ return "", history + [[message, None]]
231
+
232
+ def bot_message(history):
233
+ user_message = history[-1][0]
234
+ bot_response = chat_response(user_message, history[:-1])
235
+ history[-1][1] = bot_response
236
+ return history
237
+
238
+ def load_model_handler():
239
+ return load_model()
240
+
241
+ # Event bindings
242
+ load_btn.click(load_model_handler, outputs=status_display)
243
+
244
+ msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
245
+ bot_message, chatbot, chatbot
246
+ )
247
+ submit.click(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
248
+ bot_message, chatbot, chatbot
249
+ )
250
+ clear.click(lambda: None, None, chatbot, queue=False)
251
+
252
+ if __name__ == "__main__":
253
+ demo.launch(
254
+ server_name="0.0.0.0",
255
+ share=False,
256
+ show_error=True
257
  )