SuriRaja commited on
Commit
cb9e673
·
verified ·
1 Parent(s): 34ea069

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -39
app.py CHANGED
@@ -1,45 +1,48 @@
1
  import gradio as gr
2
- import requests
3
-
4
- # Public model URL - no API key needed
5
- HF_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
6
-
7
- def query_hf_model(messages):
8
- # Convert Gradio format (list of {"role":..., "content":...}) to prompt text
9
- prompt = "\n".join(
10
- f"{msg['role'].capitalize()}: {msg['content']}" for msg in messages if msg["role"] in {"user", "assistant"}
11
- ) + "\nAssistant:"
12
-
13
- payload = {
14
- "inputs": prompt,
15
- "parameters": {
16
- "max_new_tokens": 128,
17
- "temperature": 0.7,
18
- "return_full_text": True
19
- }
20
- }
21
-
22
- response = requests.post(HF_API_URL, json=payload)
23
- if response.status_code == 200:
24
- result = response.json()[0]["generated_text"]
25
- reply = result[len(prompt):].strip()
26
- return reply
27
- else:
28
- return f"⚠️ Error {response.status_code}: {response.reason}"
29
-
30
- def respond(user_input, chat_history):
31
- # Add user message to history
32
- chat_history.append({"role": "user", "content": user_input})
33
- reply = query_hf_model(chat_history)
34
- chat_history.append({"role": "assistant", "content": reply})
35
- return "", chat_history
36
 
37
  with gr.Blocks() as demo:
38
- gr.Markdown("### 🤖 Mistral Chatbot No Auth Required")
39
 
40
- chatbot = gr.Chatbot(label="Chat with AI", type="messages", avatar_images=("👤", "🤖"))
41
- msg = gr.Textbox(label="Your message", placeholder="Ask me anything...", scale=1)
42
 
43
- msg.submit(fn=respond, inputs=[msg, chatbot], outputs=[msg, chatbot])
 
 
44
 
45
- demo.launch(share=True)
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+
5
+ # Load model directly from Hugging Face Hub
6
+ model_name = "sshleifer/tiny-gpt2"
7
+
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(model_name)
10
+ model.eval()
11
+
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ model.to(device)
14
+
15
+ def generate_reply(messages):
16
+ # Concatenate messages into a simple prompt
17
+ prompt = "\n".join([m["content"] for m in messages])
18
+
19
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
20
+ outputs = model.generate(
21
+ **inputs,
22
+ max_new_tokens=100,
23
+ do_sample=True,
24
+ top_p=0.95,
25
+ temperature=0.7,
26
+ pad_token_id=tokenizer.eos_token_id
27
+ )
28
+
29
+ output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
30
+ # Extract the newly generated part
31
+ reply = output_text[len(prompt):].strip().split("\n")[0]
32
+ return messages + [{"role": "assistant", "content": reply}]
 
 
 
33
 
34
  with gr.Blocks() as demo:
35
+ gr.Markdown("### 🤖 Tiny GPT-2 Chatbot (No API Key, Hugging Face Model)")
36
 
37
+ chatbot = gr.Chatbot(label="Chat", type="messages")
38
+ user_input = gr.Textbox(label="Type your message here")
39
 
40
+ def on_submit(message, chat_history):
41
+ chat_history.append({"role": "user", "content": message})
42
+ return "", chat_history
43
 
44
+ user_input.submit(on_submit, [user_input, chatbot], [user_input, chatbot]).then(
45
+ generate_reply, chatbot, chatbot
46
+ )
47
+
48
+ demo.launch()