Update app.py
Browse files
app.py
CHANGED
|
@@ -2,45 +2,97 @@ import gradio as gr
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
|
|
|
| 5 |
MODEL_NAME = "microsoft/phi-2"
|
| 6 |
|
| 7 |
-
print(
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
model = AutoModelForCausalLM.from_pretrained(
|
| 10 |
MODEL_NAME,
|
| 11 |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 12 |
-
device_map="auto"
|
|
|
|
|
|
|
| 13 |
)
|
| 14 |
print("✅ Model loaded!")
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def chat_fn(message, history):
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
for user, assistant in history:
|
| 20 |
messages.append({"role": "user", "content": user})
|
| 21 |
messages.append({"role": "assistant", "content": assistant})
|
| 22 |
|
| 23 |
messages.append({"role": "user", "content": message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
inputs = tokenizer.apply_chat_template(messages, return_tensors="pt")
|
| 26 |
-
inputs = inputs.to(model.device)
|
| 27 |
|
|
|
|
| 28 |
output = model.generate(
|
| 29 |
-
inputs,
|
| 30 |
max_new_tokens=300,
|
| 31 |
temperature=0.7,
|
| 32 |
top_p=0.95,
|
| 33 |
)
|
| 34 |
|
|
|
|
| 35 |
decoded = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
return reply
|
| 39 |
|
|
|
|
| 40 |
ui = gr.ChatInterface(
|
| 41 |
chat_fn,
|
| 42 |
title="Captain Ambar — HF GPT Assistant",
|
| 43 |
-
description="Running on HuggingFace 🟦 —
|
| 44 |
)
|
| 45 |
|
| 46 |
-
ui.launch()
|
|
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
+
# Ab hum Phi-2 model use kar rahe hain
|
| 6 |
MODEL_NAME = "microsoft/phi-2"
|
| 7 |
|
| 8 |
+
print("⏳ Loading model...")
|
| 9 |
+
# Model aur Tokenizer load kar rahe hain
|
| 10 |
+
# Phi-2 ke liye trust_remote_code=True ki zarurat pad sakti hai
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
|
| 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 |
+
# Phi-2 ke liye ek simple prompt format banate hain, kyunki iska built-in chat template complex hai ya set nahi hai.
|
| 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 |
+
# History ko prepare karte hain
|
| 40 |
+
messages = []
|
| 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 |
+
# Prompt ko tokenise karte hain
|
| 52 |
+
# Phi-2 mein 'apply_chat_template' use karne ke bajaye simple encode use karna behtar hai
|
| 53 |
+
inputs = tokenizer(
|
| 54 |
+
prompt_text,
|
| 55 |
+
return_tensors="pt"
|
| 56 |
+
).to(model.device)
|
| 57 |
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
# Model se response generate karte hain
|
| 60 |
output = model.generate(
|
| 61 |
+
**inputs,
|
| 62 |
max_new_tokens=300,
|
| 63 |
temperature=0.7,
|
| 64 |
top_p=0.95,
|
| 65 |
)
|
| 66 |
|
| 67 |
+
# Generated output ko decode karte hain
|
| 68 |
decoded = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 69 |
+
|
| 70 |
+
# Phi-2 ke output se sirf naya reply extract karte hain
|
| 71 |
+
try:
|
| 72 |
+
# Generate hone ke baad, output mein bhi 'Assistant:' ke baad wala text nikalte hain
|
| 73 |
+
reply = decoded.split("Assistant:")[-1].strip()
|
| 74 |
+
# Ensure that only the generated response is taken, and not the whole history
|
| 75 |
+
|
| 76 |
+
# Upar wale split se agar poora conversation history aa raha hai,
|
| 77 |
+
# toh use history ka size pata karke sirf naya part nikalna padega.
|
| 78 |
+
# Simple extraction logic:
|
| 79 |
+
# Find the last occurrence of the user's message in the generated text
|
| 80 |
+
# and take the text that follows 'Assistant:'
|
| 81 |
+
last_assistant_index = decoded.rfind("Assistant:")
|
| 82 |
+
if last_assistant_index != -1:
|
| 83 |
+
reply = decoded[last_assistant_index + len("Assistant:"):].strip()
|
| 84 |
+
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print(f"Extraction error: {e}")
|
| 87 |
+
reply = "Sorry, I couldn't process the response properly."
|
| 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 |
+
description="Running on HuggingFace 🟦 — Microsoft Phi-2",
|
| 96 |
)
|
| 97 |
|
| 98 |
+
ui.launch()
|