kevalfst commited on
Commit
d41f38e
·
verified ·
1 Parent(s): 716f516

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -21
app.py CHANGED
@@ -1,27 +1,34 @@
 
 
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
 
4
- # Load the model
5
- model_id = "HuggingFaceH4/zephyr-7b-alpha" # or another instruct-tuned model
6
  tokenizer = AutoTokenizer.from_pretrained(model_id)
7
- model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype="auto")
8
- generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
9
 
10
- # AI Function
11
- def generate_json(prompt):
12
- system_prompt = "You are an AI that generates valid and clean JSON objects based on descriptions."
13
- input_prompt = f"{system_prompt}\n\nDescription:\n{prompt}\n\nJSON:\n"
14
- output = generator(input_prompt, max_new_tokens=256, do_sample=False)[0]["generated_text"]
15
 
16
- # Remove original prompt from generated text
17
- json_part = output.replace(input_prompt, "").strip()
18
- return json_part
 
 
 
19
 
20
- # Gradio UI
21
- gr.Interface(
22
- fn=generate_json,
23
- inputs=gr.Textbox(label="Describe the JSON you want", lines=4),
24
- outputs=gr.Textbox(label="Generated JSON", lines=20),
25
- title="🧠 JSON Generator with LLM",
26
- description="Enter a plain language description and get a structured JSON output."
27
- ).launch()
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
2
+ import torch
3
  import gradio as gr
 
4
 
5
+ # Load model and tokenizer (use public model)
6
+ model_id = "HuggingFaceH4/zephyr-7b-alpha" # or openchat/openchat-3.5
7
  tokenizer = AutoTokenizer.from_pretrained(model_id)
8
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)
9
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
10
 
11
+ # Chat memory
12
+ chat_history = []
 
 
 
13
 
14
+ # Main chat function
15
+ def chat(user_input, history):
16
+ prompt = ""
17
+ for i, (user, bot) in enumerate(history):
18
+ prompt += f"User: {user}\nAssistant: {bot}\n"
19
+ prompt += f"User: {user_input}\nAssistant:"
20
 
21
+ response = pipe(prompt, max_new_tokens=256, do_sample=True, temperature=0.7)[0]["generated_text"]
22
+ answer = response.split("Assistant:")[-1].strip()
23
+
24
+ history.append((user_input, answer))
25
+ return history, history
26
+
27
+ # Interface
28
+ chatbot = gr.Chatbot()
29
+ demo = gr.Interface(fn=chat, inputs=["text", "state"], outputs=[chatbot, "state"],
30
+ title="ChatBot",
31
+ description="Normal chatbot like ChatGPT")
32
+
33
+ if __name__ == "__main__":
34
+ demo.launch()