Spaces:
Sleeping
Sleeping
Download app.py from mathanmithun/DhiGrowth_FAQ: direct link, hf CLI and curl.
- Browser
- Download file 2.08 kB
-
https://huggingface.co/spaces/mathanmithun/DhiGrowth_FAQ/resolve/main/app.py
- Command line
-
hf download hf://spaces/mathanmithun/DhiGrowth_FAQ/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mathanmithun/DhiGrowth_FAQ/resolve/main/app.py
2.08 kB
| import torch | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| import gradio as gr | |
| MODEL_NAME = "mathanmithun/dhigrowth_qwen2p5_0_5b_merged_model" | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| torch_dtype=torch.float32, | |
| device_map="cpu" | |
| ) | |
| SYSTEM_MESSAGE = { | |
| "role": "system", | |
| "content": "You are Dhigrowth Assistant. Answer only based on Dhigrowth knowledge." | |
| } | |
| def build_prompt(messages): | |
| all_msgs = [SYSTEM_MESSAGE] + messages | |
| return tokenizer.apply_chat_template( | |
| all_msgs, | |
| tokenize=False, | |
| add_generation_prompt=True | |
| ) | |
| def respond(message, history): | |
| if history is None: | |
| history = [] | |
| # Add user message to internal storage | |
| history.append({"role": "user", "content": message}) | |
| # Prepare prompt | |
| prompt = build_prompt(history) | |
| inputs = tokenizer(prompt, return_tensors="pt") | |
| output = model.generate( | |
| **inputs, | |
| max_new_tokens=200, | |
| temperature=0.7 | |
| ) | |
| reply = tokenizer.decode(output[0], skip_special_tokens=True) | |
| # Fix repeated prefix | |
| reply = reply.split("Assistant:")[-1].strip() | |
| # Store full internal assistant response | |
| history.append({"role": "assistant", "content": reply}) | |
| # 🔥 UI RETURN FORMAT – clean (no system message) | |
| ui_history = [ | |
| {"role": msg["role"], "content": msg["content"]} | |
| for msg in history if msg["role"] != "system" | |
| ] | |
| return ui_history, history | |
| def clear_chat(): | |
| return [], [] | |
| # ---------------- UI ---------------- # | |
| with gr.Blocks() as demo: | |
| gr.Markdown("<h2 style='text-align:center;'>🤖 DhiGrowth AI Assistant</h2>") | |
| chatbot = gr.Chatbot() # expects dict messages format | |
| state = gr.State([]) | |
| text_input = gr.Textbox(placeholder="Ask something...") | |
| text_input.submit(respond, [text_input, state], [chatbot, state]) | |
| text_input.submit(lambda: "", None, text_input) | |
| gr.Button("Clear Chat").click(clear_chat, None, [chatbot, state]) | |
| demo.launch() | |