Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,41 +1,87 @@
|
|
| 1 |
from fastapi import FastAPI, Request
|
|
|
|
| 2 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
import torch
|
| 4 |
-
from
|
|
|
|
|
|
|
|
|
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
# --- Tải model ---
|
| 8 |
MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
@app.get("/")
|
| 21 |
def home():
|
| 22 |
return {"message": "API FastAI đã sẵn sàng phục vụ Túc chủ 👑"}
|
| 23 |
|
| 24 |
@app.post("/generate")
|
| 25 |
-
async def generate(request: Request):
|
| 26 |
-
|
| 27 |
-
prompt = data.get("prompt", "")
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
|
|
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
inputs = tokenizer(final_prompt, return_tensors="pt").to(model.device)
|
| 36 |
-
outputs = model.generate(
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 40 |
clean_result = result[len(final_prompt):].strip()
|
| 41 |
return {"response": clean_result}
|
|
|
|
| 1 |
from fastapi import FastAPI, Request
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
import torch
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import requests
|
| 7 |
+
import pytz
|
| 8 |
+
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
# --- Tải model ---
|
| 12 |
MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
|
| 14 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 15 |
+
MODEL_NAME,
|
| 16 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 17 |
+
device_map="auto"
|
| 18 |
+
)
|
| 19 |
|
| 20 |
+
# --- Request body ---
|
| 21 |
+
class GenerateRequest(BaseModel):
|
| 22 |
+
prompt: str
|
| 23 |
+
|
| 24 |
+
# --- Hàm lấy vị trí từ IP ---
|
| 25 |
+
def get_location_from_ip(ip: str):
|
| 26 |
+
try:
|
| 27 |
+
res = requests.get(f"https://ipinfo.io/{ip}?token=2d478668dc5662").json()
|
| 28 |
+
city = res.get("city", "Ho Chi Minh City")
|
| 29 |
+
country = res.get("country", "VN")
|
| 30 |
+
timezone = res.get("timezone", "Asia/Ho_Chi_Minh")
|
| 31 |
+
return city, country, timezone
|
| 32 |
+
except:
|
| 33 |
+
return "Ho Chi Minh City", "VN", "Asia/Ho_Chi_Minh"
|
| 34 |
|
| 35 |
@app.get("/")
|
| 36 |
def home():
|
| 37 |
return {"message": "API FastAI đã sẵn sàng phục vụ Túc chủ 👑"}
|
| 38 |
|
| 39 |
@app.post("/generate")
|
| 40 |
+
async def generate(req: GenerateRequest, request: Request):
|
| 41 |
+
prompt = req.prompt.strip()
|
|
|
|
| 42 |
|
| 43 |
+
# Lấy IP từ request
|
| 44 |
+
client_ip = request.client.host
|
| 45 |
+
city, country, timezone = get_location_from_ip(client_ip)
|
| 46 |
|
| 47 |
+
# --- Logic đặc biệt ---
|
| 48 |
+
# 1. Thời gian hiện tại
|
| 49 |
+
if "mấy giờ" in prompt or "thời gian" in prompt:
|
| 50 |
+
tz = pytz.timezone(timezone)
|
| 51 |
+
current_time = datetime.now(tz).strftime("%H:%M")
|
| 52 |
+
return {"response": f"Bây giờ ở {city} là {current_time}"}
|
| 53 |
|
| 54 |
+
# 2. Ngày hôm nay
|
| 55 |
+
if "ngày hôm nay" in prompt or "hôm nay là ngày" in prompt:
|
| 56 |
+
tz = pytz.timezone(timezone)
|
| 57 |
+
today = datetime.now(tz).strftime("%d/%m/%Y")
|
| 58 |
+
return {"response": f"Hôm nay ở {city} là ngày {today}"}
|
| 59 |
+
|
| 60 |
+
# 3. Thời tiết
|
| 61 |
+
if "thời tiết" in prompt:
|
| 62 |
+
try:
|
| 63 |
+
api_key = "YOUR_OPENWEATHER_API_KEY"
|
| 64 |
+
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={b7d49ff5de091794a9adc8ea62ef0ac7}&units=metric&lang=vi"
|
| 65 |
+
res = requests.get(url).json()
|
| 66 |
+
temp = res["main"]["temp"]
|
| 67 |
+
desc = res["weather"][0]["description"]
|
| 68 |
+
return {"response": f"Thời tiết ở {city}: {desc}, nhiệt độ {temp}°C"}
|
| 69 |
+
except:
|
| 70 |
+
return {"response": "Không lấy được dữ liệu thời tiết."}
|
| 71 |
+
|
| 72 |
+
# --- Fallback sang mô hình ---
|
| 73 |
+
final_prompt = f"Trả lời bằng tiếng Việt, ngắn gọn: {prompt}"
|
| 74 |
inputs = tokenizer(final_prompt, return_tensors="pt").to(model.device)
|
| 75 |
+
outputs = model.generate(
|
| 76 |
+
**inputs,
|
| 77 |
+
max_new_tokens=200,
|
| 78 |
+
temperature=0.3,
|
| 79 |
+
top_p=0.8,
|
| 80 |
+
do_sample=True,
|
| 81 |
+
repetition_penalty=1.2,
|
| 82 |
+
eos_token_id=tokenizer.eos_token_id
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 86 |
clean_result = result[len(final_prompt):].strip()
|
| 87 |
return {"response": clean_result}
|