Spaces:
Runtime error
Runtime error
Download app.py from Chuxia-sys/docker_merge_lora: direct link, hf CLI and curl.
- Browser
- Download file 5.82 kB
-
https://huggingface.co/spaces/Chuxia-sys/docker_merge_lora/resolve/main/app.py
- Command line
-
hf download hf://spaces/Chuxia-sys/docker_merge_lora/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Chuxia-sys/docker_merge_lora/resolve/main/app.py
5.82 kB
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import gradio as gr | |
| from fastapi import FastAPI, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| import uvicorn | |
| import time | |
| # ===================================================== | |
| # CONFIG | |
| # ===================================================== | |
| MODEL_REPO = "Chuxia-sys/finetuned_travel_model_merged" | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| # ===================================================== | |
| # LOAD MODEL | |
| # ===================================================== | |
| print(f"π§ Loading model from {MODEL_REPO} on {DEVICE.upper()}...") | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO) | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| if DEVICE == "cuda": | |
| dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16 | |
| else: | |
| dtype = torch.float32 | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_REPO, | |
| torch_dtype=dtype, | |
| low_cpu_mem_usage=True, | |
| trust_remote_code=False | |
| ).to(DEVICE) | |
| model.eval() | |
| # ===================================================== | |
| # PROMPT | |
| # ===================================================== | |
| SYSTEM_PROMPT = ( | |
| "You are a Philippine Travel planner. " | |
| "Your expertise is making detailed travel plans inside the Philippines only. " | |
| "Always respond in a helpful, friendly, and precise manner. " | |
| "Include budgets in Philippine Peso (β±), transportation types, daily itineraries, and hotel suggestions when relevant." | |
| ) | |
| # ===================================================== | |
| # GENERATE FUNCTION | |
| # ===================================================== | |
| def generate_response(message, history=None, temperature=0.7, top_p=0.9, max_new_tokens=750): | |
| if history is None: | |
| history = [] | |
| trimmed_history = history[-4:] if len(history) > 4 else history | |
| conversation = [f"<|system|> {SYSTEM_PROMPT}"] | |
| for turn in trimmed_history: | |
| role = turn["role"] | |
| content = turn["content"] | |
| if role == "user": | |
| conversation.append(f"<|instruction|> {content}") | |
| elif role == "assistant": | |
| conversation.append(f"<|response|> {content}") | |
| conversation.append(f"<|instruction|> {message}") | |
| conversation.append("<|response|>") | |
| prompt = "\n".join(conversation) | |
| inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE) | |
| start = time.time() | |
| with torch.no_grad(): | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=max_new_tokens, | |
| temperature=temperature, | |
| top_p=top_p, | |
| do_sample=True, | |
| pad_token_id=tokenizer.eos_token_id, | |
| eos_token_id=tokenizer.eos_token_id, | |
| repetition_penalty=1.1, | |
| ) | |
| elapsed = time.time() - start | |
| print(f"β‘ Generated in {elapsed:.2f}s") | |
| decoded = tokenizer.decode(outputs[0], skip_special_tokens=False) | |
| response_text = decoded.split("<|response|>")[-1].strip() if "<|response|>" in decoded else decoded.strip() | |
| if response_text and response_text[-1] not in ".!?": | |
| response_text += "." | |
| return response_text | |
| # ===================================================== | |
| # FASTAPI SETUP | |
| # ===================================================== | |
| app = FastAPI(title="Philippine Travel AI API") | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| class Query(BaseModel): | |
| message: str | |
| temperature: float = 0.7 | |
| top_p: float = 0.9 | |
| max_new_tokens: int = 512 | |
| def root(): | |
| return {"message": "π§ Philippine Travel AI Assistant API is running!"} | |
| async def generate_text(data: Query): | |
| response = generate_response( | |
| data.message, | |
| temperature=data.temperature, | |
| top_p=data.top_p, | |
| max_new_tokens=data.max_new_tokens, | |
| ) | |
| return {"input": data.message, "response": response} | |
| # ===================================================== | |
| # GRADIO UI | |
| # ===================================================== | |
| def gradio_chat(message, chat_history, temp, top_p, max_tok): | |
| if not message or not message.strip(): | |
| return chat_history, "" | |
| bot_message = generate_response(message, chat_history, temp, top_p, max_tok) | |
| chat_history.append({"role": "user", "content": message}) | |
| chat_history.append({"role": "assistant", "content": bot_message}) | |
| return chat_history, "" | |
| def clear_chat(): | |
| return [], "" | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# π§ **Philippine Travel AI Assistant** β‘") | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| temperature = gr.Slider(0.1, 1.2, value=0.7, step=0.1, label="Temperature") | |
| top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p") | |
| max_new_tokens = gr.Slider(128, 1024, value=512, step=16, label="Max New Tokens") | |
| chatbot = gr.Chatbot(height=500, type="messages", placeholder="Ask for your travel itinerary...") | |
| msg = gr.Textbox(placeholder="e.g. Plan a 3-day trip to Baguio under β±10,000", label="π¬ Your question", lines=3) | |
| with gr.Row(): | |
| send_btn = gr.Button("Send") | |
| clear_btn = gr.Button("Clear") | |
| send_btn.click(gradio_chat, inputs=[msg, chatbot, temperature, top_p, max_new_tokens], outputs=[chatbot, msg]) | |
| msg.submit(gradio_chat, inputs=[msg, chatbot, temperature, top_p, max_new_tokens], outputs=[chatbot, msg]) | |
| clear_btn.click(clear_chat, outputs=[chatbot, msg]) | |
| app = gr.mount_gradio_app(app, demo, path="/gradio") | |
| # ===================================================== | |
| # RUN | |
| # ===================================================== | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |