import gradio as gr from transformers import AutoModelForCausalLM, AutoTokenizer import torch # ✅ Naya Model Name: Qwen/Qwen2.5-0.3B-Instruct MODEL_NAME = "Qwen/Qwen2.5-0.3B-Instruct" print("⏳ Loading model...") # Model aur Tokenizer load kar rahe hain # Qwen ke liye 'trust_remote_code=True' ki zarurat nahi hai, par use rakha hai toh koi dikkat nahi tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) model = AutoModelForCausalLM.from_pretrained( MODEL_NAME, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto" ) print("✅ Model loaded!") # CUSTOM PROMPT BUILDING FUNCTION HATA DIYA HAI (Kyunki Qwen ke liye inbuilt template better hai) def chat_fn(message, history): # System prompt se conversation shuru karte hain # Note: Qwen ke official template mein system message automatically add ho jaati hai. messages = [] # History ko 'messages' list mein add karte hain, Gradio ka format use karte hue for user, assistant in history: messages.append({"role": "user", "content": user}) messages.append({"role": "assistant", "content": assistant}) # Ab user ka naya message add karte hain messages.append({"role": "user", "content": message}) # ✅ Qwen ke liye sahi template application logic: # `apply_chat_template` use kar rahe hain jo khud hi sahi format mein convert kar dega. # Agar pehle wala ValueError aaye toh `add_special_tokens=False` use kar sakte ho. # Lekin Qwen models ke latest version mein yeh theek se kaam karta hai. # Hum pehle wala (bug-free) Qwen logic use kar rahe hain, jo 7B mein kaam kar raha tha. inputs = tokenizer.apply_chat_template( messages, add_special_tokens=True, # Qwen ka default template return_tensors="pt" ) inputs = inputs.to(model.device) # Input ko model ki device (GPU/CPU) par bhejte hain # Model se response generate karte hain output = model.generate( inputs, max_new_tokens=300, temperature=0.7, top_p=0.95, # Agar response ruk jaye toh yeh zaroor daalna: eos_token_id=tokenizer.eos_token_id ) # Generated token IDs ko human-readable string mein decode karte hain decoded = tokenizer.decode(output[0], skip_special_tokens=True) # ✅ Qwen-specific reply extraction: # Qwen ke output mein poora conversation history hota hai. # Hum bas naye assistant response ko nikalenge. # Pehle poori decoded string se 'system' prompt hata do, agar woh generated output mein ho. # Example: <|im_start|>system...<|im_end|> # Phir last 'assistant' turn ke baad wala part extract karo try: # Puraani conversation se naya reply nikalne ka try # Qwen ka template `<|im_start|>assistant` se start hota hai # Sahi extraction logic: last assistant tag ke baad wala text lo. assistant_tag = tokenizer.chat_template.split("<|im_start|>assistant")[-1].split(tokenizer.eos_token)[0].strip() # Simple split logic: # decoded string se last "assistant" tag aur uske baad ke text ko nikalo # NOTE: Agar pehle wala splitting logic (jo tumne use kiya tha) fail ho, toh yeh use karo: # 1. Output se user ke last message ko nikal do, jo input mein tha. # reply_start = decoded.rfind(message) # partial_decoded = decoded[reply_start:] # 2. Simplest logic: Last message ke baad ka part nikal lo reply = decoded.split(message)[-1].strip() # Agar reply mein koi bacha hua instruction tag aa raha ho, toh use hata do if "assistant" in reply: reply = reply.split("assistant")[-1].strip() except Exception as e: print(f"Extraction error: {e}") # Agar splitting mein dikkat aaye toh poora decode kiya hua text return kar do. # User ko kam se kam response mil jayega. reply = decoded.split("assistant")[-1].strip() if "assistant" in decoded else decoded.strip() return reply # Gradio Chat Interface setup karte hain ui = gr.ChatInterface( chat_fn, title="Captain Ambar — HF GPT Assistant", # Description update kar diya hai description="Running on HuggingFace 🟦 — Qwen2.5 0.3B Instruct", ) ui.launch()