alex5757 commited on
Commit
52d1400
·
verified ·
1 Parent(s): b2beff3

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +239 -0
app.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ from peft import PeftModel
5
+ import os
6
+ from datetime import datetime
7
+
8
+ class TechWriterBot:
9
+ def __init__(self):
10
+ self.tokenizer = None
11
+ self.model = None
12
+ self.load_model()
13
+
14
+ def load_model(self):
15
+ """LoRA model yükle"""
16
+ try:
17
+ print("🔄 Model yükleniyor...")
18
+
19
+ # Base model yükle
20
+ base_model_name = "ytu-ce-cosmos/turkish-gpt2-large"
21
+ self.tokenizer = AutoTokenizer.from_pretrained(base_model_name)
22
+ base_model = AutoModelForCausalLM.from_pretrained(
23
+ base_model_name,
24
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
25
+ device_map="auto" if torch.cuda.is_available() else None
26
+ )
27
+
28
+ # LoRA adapter yükle
29
+ self.model = PeftModel.from_pretrained(base_model, ".")
30
+
31
+ print("✅ LoRA Model yüklendi!")
32
+
33
+ except Exception as e:
34
+ print(f"❌ Model yükleme hatası: {e}")
35
+ # Fallback - base model
36
+ try:
37
+ self.tokenizer = AutoTokenizer.from_pretrained("ytu-ce-cosmos/turkish-gpt2-large")
38
+ self.model = AutoModelForCausalLM.from_pretrained("ytu-ce-cosmos/turkish-gpt2-large")
39
+ print("✅ Base model yüklendi (LoRA olmadan)")
40
+ except:
41
+ self.model = None
42
+
43
+ def rewrite_article(self, text, task_type):
44
+ """Makale yeniden yaz"""
45
+ if not text.strip():
46
+ return "❌ Lütfen bir metin girin!", ""
47
+
48
+ if self.model is None:
49
+ return self.demo_response(text, task_type)
50
+
51
+ try:
52
+ # Prompt hazırla
53
+ if task_type == "Yeniden Yaz":
54
+ prompt = f"[KULLANICI] Bu haberi teknoloji sitesi yazarının üslubuyla yeniden yaz: {text[:400]} [ASISTAN]"
55
+ elif task_type == "Devam Ettir":
56
+ prompt = f"[KULLANICI] Bu başlangıcı alıp makaleyi tamamla: {text[:300]} [ASISTAN]"
57
+ else:
58
+ prompt = f"[KULLANICI] Bu haberi özetleyerek yeniden yaz: {text[:400]} [ASISTAN]"
59
+
60
+ inputs = self.tokenizer.encode(prompt, return_tensors="pt", truncation=True, max_length=512)
61
+
62
+ with torch.no_grad():
63
+ outputs = self.model.generate(
64
+ inputs,
65
+ max_length=inputs.shape[1] + 300,
66
+ temperature=0.8,
67
+ do_sample=True,
68
+ top_p=0.9,
69
+ repetition_penalty=1.1,
70
+ pad_token_id=self.tokenizer.eos_token_id
71
+ )
72
+
73
+ full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
74
+
75
+ if "[ASISTAN]" in full_response:
76
+ result = full_response.split("[ASISTAN]")[1].strip()
77
+ else:
78
+ result = full_response[len(prompt):].strip()
79
+
80
+ html_output = self.create_html_article(result)
81
+ return result, html_output
82
+
83
+ except Exception as e:
84
+ return f"❌ Hata: {str(e)}", ""
85
+
86
+ def demo_response(self, text, task_type):
87
+ """Demo yanıt"""
88
+ demo_text = f"""Peki {task_type.lower()} işlemi için harika bir örnek hazırladım!
89
+
90
+ Gelelim detaylara. Verdiğiniz metnin başlangıcı: "{text[:100]}..."
91
+
92
+ Şimdi bu metni teknoloji yazarının üslubuyla işleyeceğim. Bunun dışında metin yapısını iyileştireceğim ve daha akıcı hale getireceğim.
93
+
94
+ Son olarak da gerçek eğitilmiş model henüz tam yüklenmediği için bu demo yanıtı görüyorsunuz. LoRA adapter dosyaları yüklenince tam fonksiyon çalışacak!"""
95
+
96
+ html_demo = self.create_html_article(demo_text)
97
+ return demo_text, html_demo
98
+
99
+ def create_html_article(self, text):
100
+ """HTML makale formatı"""
101
+ paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
102
+
103
+ html_content = f"""
104
+ <div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background: #f8f9fa; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
105
+ <div style="border-bottom: 3px solid #007bff; padding-bottom: 15px; margin-bottom: 25px;">
106
+ <h1 style="color: #343a40; font-size: 28px; margin-bottom: 10px; font-weight: 600;">🚀 Teknoloji Haberi</h1>
107
+ <div style="color: #6c757d; font-size: 14px;">
108
+ 📅 {datetime.now().strftime('%d %B %Y')} | ⏱️ {len(text.split()) // 200 + 1} dk okuma | 📝 {len(text.split())} kelime
109
+ </div>
110
+ </div>
111
+ <div style="line-height: 1.8;">
112
+ """
113
+
114
+ for paragraph in paragraphs:
115
+ if len(paragraph) < 80 and any(word in paragraph.lower() for word in ['peki', 'gelelim', 'şimdi', 'son olarak', 'bunun dışında']):
116
+ html_content += f'<h2 style="color: #495057; font-size: 22px; margin: 30px 0 15px 0; border-left: 4px solid #007bff; padding-left: 15px; font-weight: 600;">{paragraph}</h2>\n'
117
+ else:
118
+ html_content += f'<p style="color: #495057; margin-bottom: 18px; text-align: justify; font-size: 16px;">{paragraph}</p>\n'
119
+
120
+ html_content += """
121
+ </div>
122
+ <div style="border-top: 2px solid #dee2e6; padding-top: 20px; margin-top: 30px; text-align: center;">
123
+ <small style="color: #6c757d; font-style: italic;">🤖 AI Teknoloji Yazarı tarafından oluşturuldu</small>
124
+ </div>
125
+ </div>
126
+ """
127
+ return html_content
128
+
129
+ # Bot instance
130
+ tech_bot = TechWriterBot()
131
+
132
+ def process_article(text, task_type, output_format):
133
+ """Ana işleme fonksiyonu"""
134
+ if not text.strip():
135
+ return "❌ Lütfen bir metin girin!", ""
136
+
137
+ rewritten_text, html_output = tech_bot.rewrite_article(text, task_type)
138
+
139
+ if output_format == "Sadece Metin":
140
+ return rewritten_text, ""
141
+ elif output_format == "Sadece HTML":
142
+ return "", html_output
143
+ else:
144
+ return rewritten_text, html_output
145
+
146
+ # Gradio interface
147
+ with gr.Blocks(title="🤖 Teknoloji Yazarı AI", theme=gr.themes.Soft()) as demo:
148
+ gr.Markdown("""
149
+ # 🤖 Teknoloji Yazarı AI
150
+
151
+ Makalenizi yapıştırın, AI yazarın üslubuyla yeniden yazsın!
152
+ **Peki**, **Gelelim**, **Şimdi** gibi geçiş kelimeleriyle teknoloji haberleri oluşturur.
153
+
154
+ > 🔥 **Fine-tuned** Turkish GPT-2 modeli ile güçlendirilmiştir
155
+ """)
156
+
157
+ with gr.Row():
158
+ with gr.Column(scale=1):
159
+ gr.Markdown("### 📝 Orijinal Makale")
160
+
161
+ original_text = gr.Textbox(
162
+ label="Makale Metni",
163
+ placeholder="Teknoloji haberi metnini buraya yapıştırın...\n\n🔥 Örnek: 'NVIDIA RTX 5090 tanıtıldı. 32GB GDDR7 bellek ile geliyor...'",
164
+ lines=12,
165
+ max_lines=20
166
+ )
167
+
168
+ task_type = gr.Radio(
169
+ choices=["Yeniden Yaz", "Devam Ettir", "Özetle"],
170
+ value="Yeniden Yaz",
171
+ label="🔧 İşlem Tipi"
172
+ )
173
+
174
+ output_format = gr.Radio(
175
+ choices=["Her İkisi", "Sadece Metin", "Sadece HTML"],
176
+ value="Her İkisi",
177
+ label="📄 Çıktı Formatı"
178
+ )
179
+
180
+ process_btn = gr.Button("🚀 AI ile İşle", variant="primary", size="lg")
181
+
182
+ with gr.Column(scale=1):
183
+ gr.Markdown("### ✨ Sonuç")
184
+
185
+ rewritten_output = gr.Textbox(
186
+ label="Yeniden Yazılan Metin",
187
+ lines=12,
188
+ max_lines=20,
189
+ interactive=False
190
+ )
191
+
192
+ html_output = gr.HTML(label="🎨 HTML Önizleme")
193
+
194
+ # Örnekler
195
+ gr.Markdown("### 📚 Örnek Metinler")
196
+ examples = [
197
+ [
198
+ "NVIDIA RTX 5090 ekran kartı nihayet tanıtıldı. Yeni kart 32GB GDDR7 bellek ile geliyor ve 575W TDP değerine sahip.",
199
+ "Yeniden Yaz",
200
+ "Her İkisi"
201
+ ],
202
+ [
203
+ "Apple iPhone 17 Pro için ilk sızıntılar gelmeye başladı. Yeni modelde kamera sistemi tamamen değişecek.",
204
+ "Devam Ettir",
205
+ "Her İkisi"
206
+ ],
207
+ [
208
+ "Google'ın yeni yapay zeka modeli Gemini 2.0 duyuruldu. Model önceki versiyona göre %40 daha iyi performans gösteriyor. Çoklu dil desteği geliştirildi ve yeni özellikler eklendi.",
209
+ "Özetle",
210
+ "Her İkisi"
211
+ ]
212
+ ]
213
+
214
+ gr.Examples(
215
+ examples=examples,
216
+ inputs=[original_text, task_type, output_format],
217
+ outputs=[rewritten_output, html_output],
218
+ fn=process_article,
219
+ cache_examples=True
220
+ )
221
+
222
+ process_btn.click(
223
+ fn=process_article,
224
+ inputs=[original_text, task_type, output_format],
225
+ outputs=[rewritten_output, html_output]
226
+ )
227
+
228
+ gr.Markdown("""
229
+ ---
230
+ ### 💡 Kullanım İpuçları:
231
+ - **Yeniden Yaz**: Mevcut haberi yazarın üslubuyla yeniden yazar
232
+ - **Devam Ettir**: Verilen başlangıcı alıp makaleyi tamamlar
233
+ - **Özetle**: Uzun metni özetleyerek yeniden yazar
234
+ - HTML çıktısını kopyalayıp web sitenizde kullanabilirsiniz!
235
+
236
+ 🔧 **Teknik**: Fine-tuned Turkish GPT-2 + LoRA adapter
237
+ """)
238
+
239
+ demo.launch()