Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
MODEL_NAME = "dali4444444/chery-sav-chatbot"
|
| 6 |
+
|
| 7 |
+
print("Loading model...")
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 9 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 10 |
+
MODEL_NAME,
|
| 11 |
+
torch_dtype=torch.float32, # CPU uses float32
|
| 12 |
+
device_map="cpu"
|
| 13 |
+
)
|
| 14 |
+
print("✅ Model ready!")
|
| 15 |
+
|
| 16 |
+
SYSTEM_PROMPT = "Tu es l'assistant SAV officiel du Centre Chery Tunisie. Tu réponds en français ou en arabe dialectal tunisien selon la langue du client."
|
| 17 |
+
|
| 18 |
+
def chat(message, history):
|
| 19 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 20 |
+
|
| 21 |
+
# Add conversation history
|
| 22 |
+
for h in history:
|
| 23 |
+
messages.append({"role": "user", "content": h[0]})
|
| 24 |
+
messages.append({"role": "assistant", "content": h[1]})
|
| 25 |
+
|
| 26 |
+
messages.append({"role": "user", "content": message})
|
| 27 |
+
|
| 28 |
+
inputs = tokenizer.apply_chat_template(
|
| 29 |
+
messages, tokenize=True,
|
| 30 |
+
add_generation_prompt=True,
|
| 31 |
+
return_tensors="pt"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
outputs = model.generate(
|
| 36 |
+
inputs, max_new_tokens=300,
|
| 37 |
+
temperature=0.7, do_sample=True
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
|
| 41 |
+
return response
|
| 42 |
+
|
| 43 |
+
# Also expose as REST API for your app
|
| 44 |
+
import json
|
| 45 |
+
from fastapi import FastAPI
|
| 46 |
+
from pydantic import BaseModel
|
| 47 |
+
|
| 48 |
+
app_api = FastAPI()
|
| 49 |
+
|
| 50 |
+
class ChatRequest(BaseModel):
|
| 51 |
+
message: str
|
| 52 |
+
history: list = []
|
| 53 |
+
|
| 54 |
+
@app_api.post("/api/chat")
|
| 55 |
+
async def api_chat(req: ChatRequest):
|
| 56 |
+
response = chat(req.message, req.history)
|
| 57 |
+
return {"reply": response}
|
| 58 |
+
|
| 59 |
+
# Gradio UI (for testing)
|
| 60 |
+
demo = gr.ChatInterface(fn=chat, title="Chery SAV Assistant")
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
demo.launch()
|