Update app.py
Browse files
app.py
CHANGED
|
@@ -2,7 +2,8 @@ import gradio as gr
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
print("π Loading model from Hugging Face...")
|
| 8 |
|
|
@@ -11,45 +12,43 @@ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
|
|
| 11 |
|
| 12 |
print("β
Model loaded!")
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
def chat(user_input):
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
return_tensors='pt'
|
| 22 |
-
)
|
| 23 |
|
| 24 |
-
|
| 25 |
-
bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1)
|
| 26 |
-
else:
|
| 27 |
-
bot_input_ids = new_input_ids
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 33 |
do_sample=True,
|
| 34 |
-
|
| 35 |
-
top_p=0.
|
| 36 |
-
|
| 37 |
)
|
| 38 |
|
| 39 |
-
response = tokenizer.decode(
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
return response
|
| 45 |
|
| 46 |
|
|
|
|
| 47 |
iface = gr.Interface(
|
| 48 |
fn=chat,
|
| 49 |
-
inputs="
|
| 50 |
outputs="text",
|
| 51 |
title="Emalawi19 AI π€",
|
| 52 |
-
description="
|
| 53 |
)
|
| 54 |
|
| 55 |
iface.launch()
|
|
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
|
| 5 |
+
# π₯ Better lightweight model
|
| 6 |
+
MODEL_NAME = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 7 |
|
| 8 |
print("π Loading model from Hugging Face...")
|
| 9 |
|
|
|
|
| 12 |
|
| 13 |
print("β
Model loaded!")
|
| 14 |
|
| 15 |
+
# πΉ Chat function
|
|
|
|
| 16 |
def chat(user_input):
|
| 17 |
+
# π₯ Strong system prompt (fixes bad answers)
|
| 18 |
+
prompt = f"""You are a helpful AI assistant.
|
| 19 |
+
You always give clear, correct, and short answers.
|
| 20 |
+
If asked for code, return clean and working code only.
|
| 21 |
|
| 22 |
+
User: {user_input}
|
| 23 |
+
Assistant:"""
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
output_ids = model.generate(
|
| 28 |
+
inputs["input_ids"],
|
| 29 |
+
max_new_tokens=150, # β‘ faster
|
|
|
|
| 30 |
do_sample=True,
|
| 31 |
+
temperature=0.7,
|
| 32 |
+
top_p=0.9,
|
| 33 |
+
repetition_penalty=1.2
|
| 34 |
)
|
| 35 |
|
| 36 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 37 |
+
|
| 38 |
+
# π₯ Clean output
|
| 39 |
+
if "Assistant:" in response:
|
| 40 |
+
response = response.split("Assistant:")[-1].strip()
|
| 41 |
|
| 42 |
return response
|
| 43 |
|
| 44 |
|
| 45 |
+
# πΉ Simple UI
|
| 46 |
iface = gr.Interface(
|
| 47 |
fn=chat,
|
| 48 |
+
inputs=gr.Textbox(placeholder="Type your message here..."),
|
| 49 |
outputs="text",
|
| 50 |
title="Emalawi19 AI π€",
|
| 51 |
+
description="Fast & smarter AI powered by Hugging Face"
|
| 52 |
)
|
| 53 |
|
| 54 |
iface.launch()
|