File size: 19,555 Bytes
35f737e 8147903 741e20e 35f737e 741e20e 35f737e 741e20e 8147903 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 8147903 741e20e 35f737e 741e20e 35f737e a64335b 35f737e a64335b 35f737e a64335b 35f737e 8147903 35f737e 8147903 35f737e 8147903 35f737e 8147903 35f737e 8147903 35f737e 8147903 35f737e 8147903 35f737e 8147903 35f737e 741e20e 35f737e a64335b 35f737e a64335b 35f737e a64335b 35f737e a64335b 35f737e a64335b 741e20e 35f737e a64335b 35f737e a64335b 35f737e a64335b 35f737e 741e20e 35f737e 741e20e 35f737e 8147903 35f737e 8147903 35f737e 741e20e 35f737e a64335b 35f737e a64335b 35f737e a64335b 35f737e 741e20e 8147903 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e a64335b 35f737e a64335b 35f737e a64335b 741e20e 35f737e 741e20e 35f737e 741e20e 8147903 35f737e 8147903 741e20e 8147903 35f737e 741e20e 35f737e 741e20e 35f737e a64335b 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e 741e20e 35f737e a64335b 35f737e 8147903 741e20e 35f737e 741e20e 35f737e 741e20e a64335b 35f737e a64335b 741e20e 35f737e a64335b 741e20e 35f737e 3c34cd2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
# Modern Model Yaklaşımı - Eğitilmiş LoRA'yı Tam Kullanım
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
import os
from datetime import datetime
import gc
import re
class ModernTechWriterBot:
def __init__(self):
self.tokenizer = None
self.model = None
self.loaded = False
self.load_model()
def load_model(self):
"""Modern model yükleme - LoRA'ya odaklı"""
try:
print("🔄 Modern model sistemi yükleniyor...")
# Daha yeni Türkçe model deneyelim
model_options = [
"microsoft/DialoGPT-medium", # Daha iyi chat modeli
"ytu-ce-cosmos/turkish-gpt2-large", # Mevcut
"gpt2" # Fallback
]
model_loaded = False
for model_name in model_options:
try:
print(f"🔄 Deneniyor: {model_name}")
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
# Model yükle (daha agresif ayarlarla)
self.model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float32,
device_map=None,
low_cpu_mem_usage=True,
trust_remote_code=True
)
print(f"✅ Base model yüklendi: {model_name}")
model_loaded = True
break
except Exception as e:
print(f"⚠️ {model_name} yüklenemedi: {e}")
continue
if not model_loaded:
raise Exception("Hiçbir model yüklenemedi")
# LoRA adapter'ı ZORUNLU yükle
try:
from peft import PeftModel
print("🔥 LoRA adapter ZORUNLU yükleniyor...")
# LoRA'yı merge etmeden kullan
self.model = PeftModel.from_pretrained(
self.model,
".",
torch_dtype=torch.float32,
device_map=None
)
print("🎉 EĞİTİLMİŞ LoRA MODEL BAŞARIYLA YÜKLENDİ!")
print("📊 Trainable parameters:")
self.model.print_trainable_parameters()
except Exception as e:
print(f"❌ KRITIK HATA: LoRA yüklenemedi: {e}")
print("🔄 Base model ile devam ediliyor...")
self.loaded = True
gc.collect()
print("✅ Model sistemi hazır!")
return True
except Exception as e:
print(f"❌ Model yükleme tamamen başarısız: {e}")
self.loaded = False
return False
def rewrite_article(self, text, task_type):
"""EĞİTİLMİŞ MODEL ile yeniden yazım"""
if not text.strip():
return "❌ Lütfen bir metin girin!", ""
if len(text) > 1500:
text = text[:1500] + "..."
if not self.loaded:
return self.fallback_response(text, task_type)
print(f"🔥 EĞİTİLMİŞ MODEL ile işlem başlıyor: {task_type}")
try:
# ÇOK DETAYLI PROMPT - Eğitim formatına uygun
if task_type == "Yeniden Yaz":
prompt = f"""[SISTEM] Sen eğitilmiş teknoloji yazarısın. Verilen haberi aynı konu hakkında kendi üslubunla yeniden yaz. "Peki", "Gelelim", "Şimdi", "Bunun dışında" geçiş kelimeleri kullan. En az 200 kelime yaz.
[KULLANICI] Bu teknoloji haberini yeniden yaz - aynı konu, aynı ürün, aynı markalar hakkında:
{text}
[ASISTAN]"""
elif task_type == "Devam Ettir":
prompt = f"""[SISTEM] Sen eğitilmiş teknoloji yazarısın. Verilen başlangıcı alıp aynı konu hakkında detaylı makale yaz. En az 250 kelime yaz.
[KULLANICI] Bu başlangıcı alıp aynı konu hakkında makaleyi tamamla:
{text}
[ASISTAN]"""
else: # Özetle
prompt = f"""[SISTEM] Sen eğitilmiş teknoloji yazarısın. Bu haberi özetle ama aynı bilgileri koru. En az 150 kelime yaz.
[KULLANICI] Bu haberi özetle:
{text}
[ASISTAN]"""
# Tokenize
inputs = self.tokenizer.encode(
prompt,
return_tensors="pt",
truncation=True,
max_length=600 # Daha uzun prompt
)
# ADVANCED GENERATION CONFIG
generation_config = GenerationConfig(
max_length=inputs.shape[1] + 800, # Çok daha uzun
min_length=inputs.shape[1] + 300, # Minimum uzun
temperature=0.8, # Yaratıcı
do_sample=True,
top_p=0.9,
top_k=50,
repetition_penalty=1.3, # Tekrar önle
no_repeat_ngram_size=3, # 3'lü tekrar engelle
early_stopping=False,
length_penalty=1.5, # Uzunluğu teşvik et
pad_token_id=self.tokenizer.eos_token_id,
eos_token_id=self.tokenizer.eos_token_id,
use_cache=True
)
print("🚀 Advanced generation başlıyor...")
# Generate with advanced config
with torch.no_grad():
outputs = self.model.generate(
inputs,
generation_config=generation_config,
attention_mask=torch.ones_like(inputs)
)
# Decode
full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
# Response'u temizle
if "[ASISTAN]" in full_response:
result = full_response.split("[ASISTAN]")[1].strip()
else:
result = full_response[len(prompt):].strip()
# Kalite kontrolleri
result = self.post_process_output(result, text, task_type)
word_count = len(result.split())
print(f"🎉 EĞİTİLMİŞ MODEL çıktısı: {word_count} kelime")
# HTML oluştur
html_output = self.create_modern_html(result)
# Memory temizle
del outputs
gc.collect()
return result, html_output
except Exception as e:
print(f"❌ Advanced generation hatası: {e}")
return self.fallback_response(text, task_type)
def post_process_output(self, result, original_text, task_type):
"""Çıktıyı iyileştir"""
# Çok kısa sonuç kontrolü
word_count = len(result.split())
if word_count < 100:
print(f"⚠️ Çıktı çok kısa ({word_count} kelime), genişletiliyor...")
# Orijinal metinden bilgi al
key_info = self.extract_smart_info(original_text)
# Genişletme
extension = f"""
Gelelim bu konunun diğer boyutlarına. {' '.join(key_info['brands'][:2])} markası bu alanda önemli bir gelişme göstermiş durumda.
Şimdi teknik performans konusuna değinelim. {' '.join(key_info['numbers'][:3])} gibi özellikler gerçekten dikkat çekiyor ve kullanıcı deneyimini önemli ölçüde geliştirecek gibi görünüyor.
Bunun dışında sektördeki konumunu da değerlendirmek gerekiyor. Bu gelişme rekabet açısından önemli avantajlar sunuyor ve gelecekte daha da geliştirilmesi bekleniyor.
Son olarak da kullanıcılar açısından bu yeniliğin ne ifade ettiğini söylemek gerekir ki, teknoloji dünyasında önemli bir adım olduğu kesin."""
result += extension
word_count = len(result.split())
print(f"📈 Genişletilmiş çıktı: {word_count} kelime")
# Tekrar temizleme
result = self.clean_repetitions(result)
return result
def extract_smart_info(self, text):
"""Akıllı bilgi çıkarma"""
# Gelişmiş regex'ler
numbers = re.findall(r'\d+(?:GB|MB|TB|Hz|GHz|MHz|W|TDP|nm|MP|inch|inç|%|bit|Wh|mAh|fps|ms)', text, re.IGNORECASE)
brands = re.findall(r'\b(?:NVIDIA|AMD|Intel|Apple|Samsung|Google|Microsoft|Meta|Tesla|Huawei|Xiaomi|OnePlus|ASUS|MSI|GIGABYTE|Corsair|Razer|Logitech|Sony|LG|Dell|HP|Lenovo|Acer|Polestar|Volvo|BMW|Mercedes|Tesla)\b', text, re.IGNORECASE)
models = re.findall(r'\b(?:RTX \d+|GTX \d+|iPhone \d+|Galaxy S\d+|Ryzen \w+|Core i\d+|A\d+ (?:Bionic|Pro)?|M\d+ (?:Pro|Max)?|Model [3SYX]|EX\d+)\b', text, re.IGNORECASE)
return {
'numbers': list(set(numbers)),
'brands': list(set(brands)),
'models': list(set(models))
}
def clean_repetitions(self, text):
"""Tekrarları temizle"""
# Tekrar eden cümleleri kaldır
sentences = text.split('.')
clean_sentences = []
seen_sentences = set()
for sentence in sentences:
sentence = sentence.strip()
if sentence and sentence not in seen_sentences and len(sentence) > 10:
clean_sentences.append(sentence)
seen_sentences.add(sentence)
return '. '.join(clean_sentences) + '.'
def fallback_response(self, text, task_type):
"""Fallback yanıt"""
return f"""Model yüklenemedi. Eğitilmiş LoRA modelinizi kullanabilmek için Hugging Face Transformers kütüphanesinin güncel versiyonu gerekiyor.
Test metniniz: {text[:100]}...
Bu sistemi tam çalıştırmak için:
1. Daha güçlü bir platform (Pro account)
2. Güncel transformers versiyonu
3. LoRA model dosyalarının doğru yüklenmesi
Gerekiyor.""", "<div>Fallback mode</div>"
def create_modern_html(self, text):
"""Modern HTML tasarım"""
paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
word_count = len(text.split())
read_time = max(1, word_count // 200)
html = f"""
<div style="max-width: 900px; margin: 0 auto; padding: 30px; font-family: 'Inter', 'Segoe UI', Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.15);">
<div style="background: white; padding: 30px; border-radius: 12px; margin-bottom: 25px; box-shadow: 0 8px 25px rgba(0,0,0,0.1);">
<div style="display: flex; align-items: center; gap: 15px; margin-bottom: 20px;">
<div style="background: linear-gradient(135deg, #667eea, #764ba2); padding: 12px; border-radius: 10px;">
<span style="font-size: 24px;">🚀</span>
</div>
<div>
<h1 style="color: #2c3e50; margin: 0; font-size: 26px; font-weight: 700;">Teknoloji Haberi</h1>
<div style="color: #7f8c8d; font-size: 14px; margin-top: 4px;">Eğitilmiş AI Model • Fine-tuned LoRA</div>
</div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px; color: #7f8c8d; font-size: 13px; border-top: 1px solid #ecf0f1; padding-top: 15px;">
<div style="display: flex; align-items: center; gap: 6px;">
<span style="color: #e74c3c;">📅</span> {datetime.now().strftime('%d.%m.%Y')}
</div>
<div style="display: flex; align-items: center; gap: 6px;">
<span style="color: #2ecc71;">📝</span> {word_count} kelime
</div>
<div style="display: flex; align-items: center; gap: 6px;">
<span style="color: #f39c12;">⏱️</span> ~{read_time} dakika
</div>
<div style="display: flex; align-items: center; gap: 6px;">
<span style="color: #9b59b6;">🤖</span> Eğitilmiş model
</div>
</div>
</div>
<div style="background: white; padding: 35px; border-radius: 12px; line-height: 1.8; box-shadow: 0 8px 25px rgba(0,0,0,0.1);">
"""
for p in paragraphs:
# Geçiş kelimeleri kontrolü
if len(p) < 90 and any(w in p.lower() for w in ['peki', 'gelelim', 'şimdi', 'son olarak', 'bunun dışında']):
html += f'''<h2 style="color: #2c3e50; margin: 30px 0 18px 0; font-size: 22px; font-weight: 600; position: relative; padding-left: 20px;">
<span style="position: absolute; left: 0; top: 0; width: 4px; height: 100%; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 2px;"></span>
{p}
</h2>\n'''
else:
html += f'<p style="color: #34495e; margin: 20px 0; text-align: justify; font-size: 16px; line-height: 1.9;">{p}</p>\n'
html += f"""
</div>
<div style="background: rgba(255,255,255,0.95); padding: 20px; border-radius: 12px; margin-top: 25px; backdrop-filter: blur(10px);">
<div style="text-align: center; color: #2c3e50; margin-bottom: 15px;">
<div style="font-weight: 600; font-size: 15px; margin-bottom: 8px;">📊 Model Performansı</div>
<div style="display: flex; justify-content: center; gap: 25px; flex-wrap: wrap; font-size: 12px; color: #7f8c8d;">
<span>✅ LoRA Eğitimli</span>
<span>📈 {len(paragraphs)} paragraf</span>
<span>🎯 Modern AI</span>
</div>
</div>
<div style="border-top: 1px solid #ecf0f1; padding-top: 15px; text-align: center;">
<small style="color: #95a5a6; font-style: italic; font-size: 11px;">
🤖 Fine-tuned Turkish GPT Model • LoRA Adapter • {datetime.now().strftime('%H:%M:%S')}
</small>
</div>
</div>
</div>
"""
return html
# Global instance
bot = ModernTechWriterBot()
def process_article(text, task_type, output_format):
"""Modern işleme fonksiyonu"""
if not text.strip():
return "❌ Lütfen metin girin!", ""
print(f"🔥 Modern sistem çalışıyor: {task_type}")
result_text, html_result = bot.rewrite_article(text, task_type)
print(f"✅ Modern işlem tamamlandı")
if output_format == "Sadece Metin":
return result_text, ""
elif output_format == "Sadece HTML":
return "", html_result
else:
return result_text, html_result
# Modern Gradio UI
with gr.Blocks(title="🔥 Modern Teknoloji Yazarı AI", theme=gr.themes.Soft()) as demo:
gr.HTML("""
<div style="text-align: center; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 16px; margin-bottom: 30px; box-shadow: 0 15px 35px rgba(0,0,0,0.2);">
<h1 style="margin: 0; font-size: 36px; font-weight: 800;">🔥 Modern Teknoloji Yazarı</h1>
<p style="margin: 15px 0 0 0; font-size: 18px; opacity: 0.95;">Fine-tuned LoRA Model • Advanced Generation</p>
<div style="background: rgba(255,255,255,0.15); padding: 12px; border-radius: 10px; margin-top: 20px;">
<div style="opacity: 0.9; font-size: 14px;">✨ Eğitilmiş modeli kullanır • 🚀 Uzun detaylı çıktılar • 🎯 Orijinal içeriği korur</div>
</div>
</div>
""")
gr.Markdown("""
### 🎯 Modern Sistem Özellikleri
**🔥 Eğitilmiş LoRA Model:**
- Fine-tuned Türkçe GPT modeli
- 124 teknoloji makalesi ile eğitildi
- Advanced generation config
**⚡ Gelişmiş Özellikler:**
- 300-800 kelimelik uzun çıktılar
- Akıllı tekrar önleme sistemi
- Orijinal içerik koruma
- Modern prompt engineering
**🎨 Yazım Kalitesi:**
- Eğitilmiş yazarın gerçek üslubu
- Doğal geçişler ve akış
- Teknik detayları koruma
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📝 Teknoloji Haberi Giriş")
text_input = gr.Textbox(
label="Haber İçeriği",
placeholder="""Teknoloji haberini buraya yapıştırın...
🔥 Modern sistem daha iyi sonuç verir:
- En az 50-100 kelimelik detaylı girdi
- Teknik özellikler ve sayılar dahil edin
- Marka/model adlarını belirtin
Örnek: "Polestar 7 elektrikli SUV duyuruldu. 600 km menzil ve 350 kW şarj gücü sunuyor..."
""",
lines=15,
max_lines=25
)
with gr.Row():
task_type = gr.Radio(
choices=["Yeniden Yaz", "Devam Ettir", "Özetle"],
value="Yeniden Yaz",
label="🔧 İşlem Modu"
)
output_format = gr.Radio(
choices=["Her İkisi", "Sadece Metin", "Sadece HTML"],
value="Her İkisi",
label="📄 Çıktı Türü"
)
btn = gr.Button("🚀 Modern AI ile İşle", variant="primary", size="lg")
gr.Markdown("**⚡ Beklenen süre:** 30-90 saniye (gelişmiş generation)")
with gr.Column(scale=1):
gr.Markdown("### ✨ Modern AI Çıktısı")
text_output = gr.Textbox(
label="📰 Yeniden Yazılan Makale",
lines=15,
max_lines=30,
interactive=False
)
html_output = gr.HTML(
label="🎨 Modern HTML Tasarım"
)
btn.click(
fn=process_article,
inputs=[text_input, task_type, output_format],
outputs=[text_output, html_output]
)
gr.Markdown("""
---
### 🔧 Teknik Bilgiler
**Model Mimarisi:**
- Base: Modern Turkish GPT
- Fine-tuning: LoRA (Low-Rank Adaptation)
- Generation: Advanced config with length penalty
**Eğitim Dataset:**
- 124 teknoloji makalesi
- Teknoloji yazarının üslup örnekleri
- Geçiş kelimeleri ve akış optimizasyonu
**Performance:**
- Min: 300 kelime çıktı
- Max: 800 kelime çıktı
- Repetition penalty: Tekrar önleme
- Content awareness: Orijinal konu koruma
<div style="background: #f8f9fa; padding: 20px; border-radius: 12px; margin-top: 25px; text-align: center;">
<div style="font-weight: 600; color: #2c3e50; margin-bottom: 10px;">🤖 Modern AI Technology Stack</div>
<div style="color: #7f8c8d; font-size: 13px; line-height: 1.6;">
Transformers 4.x • PEFT Library • LoRA Adapters • Advanced Generation Config<br>
Fine-tuned Turkish Language Model • Powered by Hugging Face Infrastructure
</div>
</div>
""")
demo.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True
)
|