Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
import requests
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# ==== Hugging Face Inference API (Vit5 chatbot) ====
|
| 10 |
+
HF_CHATBOT_MODEL = "lingling707/vit5-skinbot"
|
| 11 |
+
HF_CHATBOT_URL = f"https://api-inference.huggingface.co/models/{HF_CHATBOT_MODEL}"
|
| 12 |
+
|
| 13 |
+
# ==== Hugging Face Inference API (Skin classification) ====
|
| 14 |
+
HF_IMAGE_MODEL = "dima806/skin_types_image_detection"
|
| 15 |
+
HF_IMAGE_URL = f"https://router.huggingface.co/hf-inference/models/{HF_IMAGE_MODEL}"
|
| 16 |
+
|
| 17 |
+
# Nếu model public thì headers có thể để {}
|
| 18 |
+
# Nếu private thì set token trong Render → Environment Variables: HF_API_TOKEN
|
| 19 |
+
HF_HEADERS = {}
|
| 20 |
+
if "HF_TOKEN" in os.environ:
|
| 21 |
+
HF_HEADERS = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}
|
| 22 |
+
|
| 23 |
+
# ==== FastAPI setup ====
|
| 24 |
+
app = FastAPI()
|
| 25 |
+
app.add_middleware(
|
| 26 |
+
CORSMiddleware,
|
| 27 |
+
allow_origins=["*"],
|
| 28 |
+
allow_credentials=True,
|
| 29 |
+
allow_methods=["*"],
|
| 30 |
+
allow_headers=["*"],
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# ==== Request body ====
|
| 34 |
+
class RequestData(BaseModel):
|
| 35 |
+
userMessage: str
|
| 36 |
+
imageUrl: Optional[str] = None
|
| 37 |
+
|
| 38 |
+
# ==== Map label sang mô tả tiếng Việt ====
|
| 39 |
+
def map_labels_to_skin_type(label: str):
|
| 40 |
+
label = label.lower()
|
| 41 |
+
if label in ["acne", "pimple", "oily"]:
|
| 42 |
+
return "da dầu, dễ nổi mụn"
|
| 43 |
+
elif label in ["dry", "wrinkle"]:
|
| 44 |
+
return "da khô, có thể bong tróc hoặc lão hóa sớm"
|
| 45 |
+
elif label in ["redness", "sensitive"]:
|
| 46 |
+
return "da nhạy cảm"
|
| 47 |
+
elif label in ["blemish", "freckles"]:
|
| 48 |
+
return "da hỗn hợp"
|
| 49 |
+
elif label == "normal":
|
| 50 |
+
return "da thường, cân bằng"
|
| 51 |
+
else:
|
| 52 |
+
return "không xác định rõ loại da"
|
| 53 |
+
|
| 54 |
+
# ==== Hàm gọi HF API (chatbot) ====
|
| 55 |
+
def query_chatbot(prompt: str):
|
| 56 |
+
try:
|
| 57 |
+
response = requests.post(
|
| 58 |
+
HF_CHATBOT_URL,
|
| 59 |
+
headers=HF_HEADERS,
|
| 60 |
+
json={"input": prompt}
|
| 61 |
+
)
|
| 62 |
+
if response.status_code == 200:
|
| 63 |
+
data = response.json()
|
| 64 |
+
if isinstance(data, list) and len(data) > 0 and "generated_text" in data[0]:
|
| 65 |
+
return data[0]["generated_text"].strip()
|
| 66 |
+
return "Xin lỗi, mình chưa có câu trả lời phù hợp."
|
| 67 |
+
else:
|
| 68 |
+
print("HF chatbot API error:", response.text)
|
| 69 |
+
return "Xin lỗi, bot chưa trả lời được. Vui lòng thử lại."
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print("HF chatbot API exception:", e)
|
| 72 |
+
return "Có lỗi khi gọi Hugging Face API."
|
| 73 |
+
|
| 74 |
+
# ==== Hàm gọi HF API (image model) ====
|
| 75 |
+
def analyze_image(url: str):
|
| 76 |
+
try:
|
| 77 |
+
response = requests.post(
|
| 78 |
+
HF_IMAGE_URL,
|
| 79 |
+
headers=HF_HEADERS,
|
| 80 |
+
json={"inputs": url}
|
| 81 |
+
)
|
| 82 |
+
if response.status_code == 200:
|
| 83 |
+
results = response.json()
|
| 84 |
+
if isinstance(results, list) and len(results) > 0:
|
| 85 |
+
top = max(results, key=lambda x: x.get("score", 0))
|
| 86 |
+
return top["label"]
|
| 87 |
+
print("HF image API error:", response.text)
|
| 88 |
+
return None
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print("HF image API exception:", e)
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
# ==== Routes ====
|
| 94 |
+
@app.get("/")
|
| 95 |
+
async def root():
|
| 96 |
+
return {"message": "Skin Advisor API (Vit5 + Skin Classification via HF API) is running 🚀"}
|
| 97 |
+
|
| 98 |
+
@app.post("/skinAdvisor")
|
| 99 |
+
async def skin_advisor(data: RequestData):
|
| 100 |
+
skin_analysis = ""
|
| 101 |
+
|
| 102 |
+
# Nếu có ảnh thì gọi API phân tích da
|
| 103 |
+
if data.imageUrl and data.imageUrl.startswith(("http://", "https://")):
|
| 104 |
+
label = analyze_image(data.imageUrl)
|
| 105 |
+
if label:
|
| 106 |
+
skin_type = map_labels_to_skin_type(label)
|
| 107 |
+
skin_analysis = f"Ảnh phân tích cho thấy: {skin_type}."
|
| 108 |
+
else:
|
| 109 |
+
skin_analysis = "Không thể phân tích ảnh da."
|
| 110 |
+
|
| 111 |
+
# Ghép prompt cho chatbot
|
| 112 |
+
if skin_analysis:
|
| 113 |
+
prompt = (
|
| 114 |
+
f"Bạn là chuyên gia tư vấn chăm sóc da. "
|
| 115 |
+
f"{skin_analysis} "
|
| 116 |
+
f"Người dùng hỏi: {data.userMessage}. "
|
| 117 |
+
"Hãy trả lời ngắn gọn, thân thiện, bằng tiếng Việt, "
|
| 118 |
+
"gồm cả nhận xét về tình trạng da và gợi ý phương hướng chăm sóc. "
|
| 119 |
+
"Tuyệt đối không gợi ý nguy hiểm."
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
prompt = (
|
| 123 |
+
"Bạn là chuyên gia tư vấn chăm sóc da. "
|
| 124 |
+
f"Người dùng hỏi: {data.userMessage}. "
|
| 125 |
+
"Hãy trả lời ngắn gọn, thân thiện, bằng tiếng Việt, "
|
| 126 |
+
"chỉ tư vấn chăm sóc da, tuyệt đối không gợi ý nguy hiểm."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
reply = query_chatbot(prompt)
|
| 130 |
+
return {"reply": reply}
|