import gradio as gr import json import time import os from datetime import datetime from llm_utils import LLM_PROVIDERS, get_llm_models, validate_api_key, call_llm, parse_llm_output, create_zip_from_files from project_types import PROJECT_TYPES from advanced_prompts import ( get_advanced_context_prompt, get_advanced_commands_prompt, get_advanced_prompts_prompt, calculate_project_complexity, get_industry_specific_requirements ) # Global state generated_files = {'context': {}, 'commands': {}, 'prompts': {}} stats = {'context': {'tokens': 0, 'time': 0}, 'commands': {'tokens': 0, 'time': 0}, 'prompts': {'tokens': 0, 'time': 0}} project_analysis = {} # Sektörler INDUSTRIES = [ "Teknoloji/Yazılım", "Finans/Fintech", "Sağlık/Healthcare", "E-ticaret", "Eğitim/EdTech", "Oyun/Gaming", "Sosyal Medya", "IoT/Akıllı Cihazlar", "Blockchain/Web3", "AI/ML Servisleri", "SaaS B2B", "SaaS B2C", "Marketplace", "Diğer" ] # Proje özellikleri PROJECT_FEATURES = [ "Kullanıcı Yönetimi", "Ödeme İşlemleri", "Gerçek Zamanlı Özellikler", "AI/ML Entegrasyonu", "Çoklu Platform", "3. Parti Entegrasyonlar", "Offline Çalışma", "Çoklu Dil Desteği", "Bildirim Sistemi", "Analytics/Raporlama", "Sosyal Özellikler", "Güvenlik/Compliance" ] def analyze_project(project_type, project_idea, industry, features): """Proje analizi yapar ve öneriler üretir""" analysis = { "complexity": calculate_project_complexity(project_type, project_idea, features), "industry_requirements": get_industry_specific_requirements(industry), "estimated_files": {}, "tech_recommendations": [], "architecture_suggestion": "" } # Teknoloji önerileri if "AI/ML" in project_type: analysis["tech_recommendations"] = ["Python", "TensorFlow/PyTorch", "MLflow", "Docker", "Kubernetes"] analysis["architecture_suggestion"] = "Microservices with ML Pipeline" elif "Web" in project_type: analysis["tech_recommendations"] = ["React/Next.js", "Node.js/Python", "PostgreSQL", "Redis", "Docker"] analysis["architecture_suggestion"] = "Modern Jamstack Architecture" elif "Mobil" in project_type: analysis["tech_recommendations"] = ["React Native/Flutter", "Firebase", "GraphQL", "Redux/MobX"] analysis["architecture_suggestion"] = "Clean Architecture with BLoC/MVVM" return analysis def generate_section_advanced(provider, model, api_key, project_type, project_idea, section, industry, features, tech_details, progress=gr.Progress()): """Gelişmiş section oluşturma""" try: start_time = time.time() # Proje analizi progress(0.05, desc="Proje analiz ediliyor...") analysis = analyze_project(project_type, project_idea, industry, features) global project_analysis project_analysis = analysis # Progress progress(0.1, desc=f"{section.capitalize()} için akıllı prompt hazırlanıyor...") # Section'a göre advanced prompt seç if section == 'context': prompt = get_advanced_context_prompt(project_type, project_idea, tech_details) elif section == 'commands': context_summary = f"Proje {len(generated_files['context'])} context dosyası içeriyor" prompt = get_advanced_commands_prompt(project_type, project_idea, context_summary) elif section == 'prompts': prompt = get_advanced_prompts_prompt(project_type, project_idea, tech_details) # Sektör gereksinimlerini ekle if industry != "Diğer": prompt += f"\n\nSEKTÖR GEREKSİNİMLERİ ({industry}):\n" prompt += "\n".join(f"- {req}" for req in analysis["industry_requirements"]) # Token tahmini prompt_tokens = len(prompt.split()) * 1.3 progress(0.3, desc="AI ile iletişim kuruluyor...") # LLM çağrısı llm_response = call_llm(provider, model, api_key, prompt) if not llm_response or "hata" in llm_response.lower(): return f"
❌ Hata: {llm_response}
", None, None progress(0.6, desc="Yanıt işleniyor ve optimize ediliyor...") # Response analizi response_tokens = len(llm_response.split()) * 1.3 total_tokens = prompt_tokens + response_tokens # Dosyaları parse et parsed_files = parse_llm_output(llm_response) if not parsed_files: return f"❌ Dosyalar ayrıştırılamadı.
", None, None # Kaydet generated_files[section] = parsed_files # İstatistikleri güncelle elapsed_time = time.time() - start_time stats[section] = {'tokens': int(total_tokens), 'time': round(elapsed_time, 2)} progress(0.9, desc="Kalite kontrolü yapılıyor...") # Dosya listesi ve kalite skoru file_count = len(parsed_files) quality_score = min(100, 60 + (file_count * 4)) # Basit kalite skoru # Başarı mesajı file_list_html = "❌ Hata: {str(e)}
{error_detail}", None, None
def download_all_professional():
"""Profesyonel ZIP paketi oluşturur"""
all_files = {}
# Dosyaları topla
for section in ['context', 'commands', 'prompts']:
if generated_files[section]:
all_files.update(generated_files[section])
if not all_files:
return None, "❌ İndirilecek dosya yok.
" # README.md oluştur readme_content = f"""# {project_analysis.get('project_name', 'Project')} - Context Engineering ## 📋 Proje Özeti - **Tür:** {project_analysis.get('project_type', 'N/A')} - **Sektör:** {project_analysis.get('industry', 'N/A')} - **Karmaşıklık:** {project_analysis.get('complexity', {}).get('context', 0) + project_analysis.get('complexity', {}).get('commands', 0) + project_analysis.get('complexity', {}).get('prompts', 0)} puan ## 📁 Dosya Yapısı - `context/` - Proje bağlamı ve dokümantasyon ({len(generated_files['context'])} dosya) - `commands/` - Otomasyon ve yönetim komutları ({len(generated_files['commands'])} dosya) - `prompts/` - AI asistan prompt şablonları ({len(generated_files['prompts'])} dosya) ## 🚀 Başlangıç 1. Context dosyalarını okuyarak projeyi anlayın 2. Commands klasöründeki setup komutlarını çalıştırın 3. Prompts şablonlarını AI asistanınızla kullanın ## 📊 İstatistikler - Toplam Dosya: {len(all_files)} - Toplam Token: ~{sum(s['tokens'] for s in stats.values())} - Oluşturma Süresi: {sum(s['time'] for s in stats.values()):.1f} saniye --- Generated by Context Engineer v2.0 """ all_files['README.md'] = readme_content # Manifest dosyası manifest = { "version": "2.0", "generated_at": datetime.now().isoformat(), "statistics": stats, "project_analysis": project_analysis, "file_count": { "context": len(generated_files['context']), "commands": len(generated_files['commands']), "prompts": len(generated_files['prompts']) } } all_files['manifest.json'] = json.dumps(manifest, indent=2) # ZIP oluştur zip_data = create_zip_from_files(all_files) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") zip_file_path = f"./context_engineering_pro_{timestamp}.zip" with open(zip_file_path, "wb") as f: f.write(zip_data) # Özet rapor total_size_kb = sum(len(content.encode('utf-8')) for content in all_files.values()) / 1024 summary = f"""✨ Profesyonel context engineering paketiniz başarıyla oluşturuldu!
⚠️ Sağlayıcı ve API anahtarı gerekli.
"), gr.Dropdown() is_valid, message = validate_api_key(provider, api_key) if is_valid: models = get_llm_models(provider, api_key) return ( gr.Markdown(f"✅ {message}
"), gr.Dropdown(choices=models, value=models[0] if models else None, interactive=True) ) return ( gr.Markdown(f"❌ {message}
"), gr.Dropdown(choices=[], interactive=False) ) def analyze_project_details(project_type, project_idea, industry, features): analysis = analyze_project(project_type, project_idea, industry, features) report = f"""{analysis['architecture_suggestion']}