Update app.py
Browse files
app.py
CHANGED
|
@@ -2,97 +2,107 @@ import gradio as gr
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
-
#
|
| 6 |
MODEL_NAME = "Qwen/Qwen2.5-0.3B-Instruct"
|
| 7 |
|
| 8 |
print("⏳ Loading model...")
|
| 9 |
# Model aur Tokenizer load kar rahe hain
|
| 10 |
-
#
|
| 11 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME
|
| 12 |
model = AutoModelForCausalLM.from_pretrained(
|
| 13 |
MODEL_NAME,
|
| 14 |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 15 |
-
device_map="auto"
|
| 16 |
-
# Phi-2 ke liye bhi trust_remote_code=True ki zarurat pad sakti hai
|
| 17 |
-
trust_remote_code=True
|
| 18 |
)
|
| 19 |
print("✅ Model loaded!")
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
# Phi-2 mostly simple text inputs par train hota hai, isliye hum "Instruct" format bana rahe hain.
|
| 23 |
-
def build_prompt(messages):
|
| 24 |
-
prompt = "You are a helpful AI assistant.\n"
|
| 25 |
-
|
| 26 |
-
# History ko 'User: ... Assistant: ...' format mein daalte hain
|
| 27 |
-
for msg in messages:
|
| 28 |
-
if msg["role"] == "user":
|
| 29 |
-
prompt += f"User: {msg['content']}\n"
|
| 30 |
-
elif msg["role"] == "assistant":
|
| 31 |
-
prompt += f"Assistant: {msg['content']}\n"
|
| 32 |
-
|
| 33 |
-
# Model ko batate hain ki ab Assistant ki baari hai
|
| 34 |
-
prompt += "Assistant:"
|
| 35 |
-
return prompt.strip()
|
| 36 |
-
|
| 37 |
|
| 38 |
def chat_fn(message, history):
|
| 39 |
-
#
|
| 40 |
-
|
|
|
|
| 41 |
|
|
|
|
| 42 |
for user, assistant in history:
|
| 43 |
messages.append({"role": "user", "content": user})
|
| 44 |
messages.append({"role": "assistant", "content": assistant})
|
| 45 |
|
|
|
|
| 46 |
messages.append({"role": "user", "content": message})
|
| 47 |
-
|
| 48 |
-
# Custom prompt function use karte hain
|
| 49 |
-
prompt_text = build_prompt(messages)
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
#
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
return_tensors="pt"
|
| 56 |
-
)
|
| 57 |
-
|
| 58 |
|
| 59 |
# Model se response generate karte hain
|
| 60 |
output = model.generate(
|
| 61 |
-
|
| 62 |
max_new_tokens=300,
|
| 63 |
temperature=0.7,
|
| 64 |
top_p=0.95,
|
|
|
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
-
# Generated
|
| 68 |
decoded = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 69 |
|
| 70 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
-
#
|
| 73 |
-
|
| 74 |
-
# Ensure that only the generated response is taken, and not the whole history
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
#
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
except Exception as e:
|
| 86 |
print(f"Extraction error: {e}")
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
| 89 |
return reply
|
| 90 |
|
| 91 |
# Gradio Chat Interface setup karte hain
|
| 92 |
ui = gr.ChatInterface(
|
| 93 |
chat_fn,
|
| 94 |
title="Captain Ambar — HF GPT Assistant",
|
| 95 |
-
|
|
|
|
| 96 |
)
|
| 97 |
|
| 98 |
ui.launch()
|
|
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
+
# ✅ Naya Model Name: Qwen/Qwen2.5-0.3B-Instruct
|
| 6 |
MODEL_NAME = "Qwen/Qwen2.5-0.3B-Instruct"
|
| 7 |
|
| 8 |
print("⏳ Loading model...")
|
| 9 |
# Model aur Tokenizer load kar rahe hain
|
| 10 |
+
# Qwen ke liye 'trust_remote_code=True' ki zarurat nahi hai, par use rakha hai toh koi dikkat nahi
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 12 |
model = AutoModelForCausalLM.from_pretrained(
|
| 13 |
MODEL_NAME,
|
| 14 |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 15 |
+
device_map="auto"
|
|
|
|
|
|
|
| 16 |
)
|
| 17 |
print("✅ Model loaded!")
|
| 18 |
|
| 19 |
+
# CUSTOM PROMPT BUILDING FUNCTION HATA DIYA HAI (Kyunki Qwen ke liye inbuilt template better hai)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def chat_fn(message, history):
|
| 22 |
+
# System prompt se conversation shuru karte hain
|
| 23 |
+
# Note: Qwen ke official template mein system message automatically add ho jaati hai.
|
| 24 |
+
messages = []
|
| 25 |
|
| 26 |
+
# History ko 'messages' list mein add karte hain, Gradio ka format use karte hue
|
| 27 |
for user, assistant in history:
|
| 28 |
messages.append({"role": "user", "content": user})
|
| 29 |
messages.append({"role": "assistant", "content": assistant})
|
| 30 |
|
| 31 |
+
# Ab user ka naya message add karte hain
|
| 32 |
messages.append({"role": "user", "content": message})
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# ✅ Qwen ke liye sahi template application logic:
|
| 35 |
+
# `apply_chat_template` use kar rahe hain jo khud hi sahi format mein convert kar dega.
|
| 36 |
+
# Agar pehle wala ValueError aaye toh `add_special_tokens=False` use kar sakte ho.
|
| 37 |
+
# Lekin Qwen models ke latest version mein yeh theek se kaam karta hai.
|
| 38 |
+
|
| 39 |
+
# Hum pehle wala (bug-free) Qwen logic use kar rahe hain, jo 7B mein kaam kar raha tha.
|
| 40 |
+
inputs = tokenizer.apply_chat_template(
|
| 41 |
+
messages,
|
| 42 |
+
add_special_tokens=True, # Qwen ka default template
|
| 43 |
return_tensors="pt"
|
| 44 |
+
)
|
| 45 |
+
inputs = inputs.to(model.device) # Input ko model ki device (GPU/CPU) par bhejte hain
|
| 46 |
|
| 47 |
# Model se response generate karte hain
|
| 48 |
output = model.generate(
|
| 49 |
+
inputs,
|
| 50 |
max_new_tokens=300,
|
| 51 |
temperature=0.7,
|
| 52 |
top_p=0.95,
|
| 53 |
+
# Agar response ruk jaye toh yeh zaroor daalna:
|
| 54 |
+
eos_token_id=tokenizer.eos_token_id
|
| 55 |
)
|
| 56 |
|
| 57 |
+
# Generated token IDs ko human-readable string mein decode karte hain
|
| 58 |
decoded = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 59 |
|
| 60 |
+
# ✅ Qwen-specific reply extraction:
|
| 61 |
+
# Qwen ke output mein poora conversation history hota hai.
|
| 62 |
+
# Hum bas naye assistant response ko nikalenge.
|
| 63 |
+
|
| 64 |
+
# Pehle poori decoded string se 'system' prompt hata do, agar woh generated output mein ho.
|
| 65 |
+
# Example: <|im_start|>system...<|im_end|>
|
| 66 |
+
|
| 67 |
+
# Phir last 'assistant' turn ke baad wala part extract karo
|
| 68 |
try:
|
| 69 |
+
# Puraani conversation se naya reply nikalne ka try
|
| 70 |
+
# Qwen ka template `<|im_start|>assistant` se start hota hai
|
|
|
|
| 71 |
|
| 72 |
+
# Sahi extraction logic: last assistant tag ke baad wala text lo.
|
| 73 |
+
assistant_tag = tokenizer.chat_template.split("<|im_start|>assistant")[-1].split(tokenizer.eos_token)[0].strip()
|
| 74 |
+
|
| 75 |
+
# Simple split logic:
|
| 76 |
+
# decoded string se last "assistant" tag aur uske baad ke text ko nikalo
|
| 77 |
+
|
| 78 |
+
# NOTE: Agar pehle wala splitting logic (jo tumne use kiya tha) fail ho, toh yeh use karo:
|
| 79 |
+
|
| 80 |
+
# 1. Output se user ke last message ko nikal do, jo input mein tha.
|
| 81 |
+
# reply_start = decoded.rfind(message)
|
| 82 |
+
# partial_decoded = decoded[reply_start:]
|
| 83 |
+
|
| 84 |
+
# 2. Simplest logic: Last message ke baad ka part nikal lo
|
| 85 |
+
reply = decoded.split(message)[-1].strip()
|
| 86 |
+
|
| 87 |
+
# Agar reply mein koi bacha hua instruction tag aa raha ho, toh use hata do
|
| 88 |
+
if "assistant" in reply:
|
| 89 |
+
reply = reply.split("assistant")[-1].strip()
|
| 90 |
+
|
| 91 |
except Exception as e:
|
| 92 |
print(f"Extraction error: {e}")
|
| 93 |
+
# Agar splitting mein dikkat aaye toh poora decode kiya hua text return kar do.
|
| 94 |
+
# User ko kam se kam response mil jayega.
|
| 95 |
+
reply = decoded.split("assistant")[-1].strip() if "assistant" in decoded else decoded.strip()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
return reply
|
| 99 |
|
| 100 |
# Gradio Chat Interface setup karte hain
|
| 101 |
ui = gr.ChatInterface(
|
| 102 |
chat_fn,
|
| 103 |
title="Captain Ambar — HF GPT Assistant",
|
| 104 |
+
# Description update kar diya hai
|
| 105 |
+
description="Running on HuggingFace 🟦 — Qwen2.5 0.3B Instruct",
|
| 106 |
)
|
| 107 |
|
| 108 |
ui.launch()
|