import gradio as gr from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import torch # ---------------------------- # 1. MODEL YÜKLEME (Lazy) # ---------------------------- model = None tokenizer = None def model_yukle(): global model, tokenizer if model is not None: return from transformers import AutoModelForCausalLM, AutoTokenizer print("🔄 Model yükleniyor...") tokenizer = AutoTokenizer.from_pretrained( "VoidOaz/Timur1Flash", trust_remote_code=True, ) model = AutoModelForCausalLM.from_pretrained( "VoidOaz/Timur1Flash", dtype=torch.float32, device_map="cpu", trust_remote_code=True, ) print("✅ Model hazır") # ---------------------------- # 2. GRADIO ARAYÜZÜ (Sadece "Running" olması için) # ---------------------------- def gradio_sohbet(mesaj, gecmis): model_yukle() # (Burada da modeli çalıştırabilirsin, ama Vercel için gerek yok) return "Bu arayüz test amaçlıdır. Vercel'den /sohbet endpoint'ini kullanın." with gr.Blocks() as demo: gr.Markdown("# 🤖 Timur 1 Flash") gr.Markdown("Vercel'den `/sohbet` endpoint'ine POST isteği atın.") chatbot = gr.Chatbot() msg = gr.Textbox(placeholder="Mesaj yaz...") msg.submit(gradio_sohbet, [msg, chatbot], [chatbot]) # ---------------------------- # 3. FASTAPI + CORS + ÖZEL ENDPOINT # ---------------------------- app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], # Vercel domain'ini sonra kısıtlayabilirsin allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class Soru(BaseModel): mesaj: str @app.post("/sohbet") async def sohbet(soru: Soru): model_yukle() mesajlar = [ {"role": "system", "content": "Sen Timur AI adında zeki ve yardımcı bir yapay zeka asistanısın."}, {"role": "user", "content": soru.mesaj}, ] metin = tokenizer.apply_chat_template(mesajlar, tokenize=False, add_generation_prompt=True) girdi = tokenizer(metin, return_tensors="pt") with torch.no_grad(): cikti = model.generate( **girdi, max_new_tokens=150, do_sample=True, temperature=0.7, pad_token_id=tokenizer.eos_token_id, ) cevap = tokenizer.decode(cikti[0][girdi["input_ids"].shape[1]:], skip_special_tokens=True) return {"cevap": cevap.strip()} @app.get("/") def root(): return {"durum": "Timur 1 Flash çalışıyor"} # ---------------------------- # 4. GRADIO'YU FASTAPI'YE MOUNT ET # ---------------------------- app = gr.mount_gradio_app(app, demo, path="/")