Remind / app.py
phuoctaiismee
Map unsupported content types to HF supported ones
73ac4f1
Raw History Blame Contribute Delete
18 kB
import os
import re
import requests
import tempfile
from datetime import datetime, timedelta
from typing import Optional
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
# ---------------------------------------------------------------------------
# App setup
# ---------------------------------------------------------------------------
app = FastAPI(
title="Remind - Voice Task Creator",
description="API nhận file ghi âm giọng nói, chuyển thành văn bản bằng Whisper, "
"sau đó phân tích và trích xuất Task tiếng Việt trả về JSON.",
version="1.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# Hugging Face Serverless Inference API config
# ---------------------------------------------------------------------------
HF_API_URL = "https://router.huggingface.co/hf-inference/models/openai/whisper-large-v3-turbo"
HF_TOKEN = os.environ.get("HF_TOKEN", "")
ALLOWED_AUDIO_TYPES = {
# MP3 & MPEG gia đình
"audio/mpeg", "audio/mp3", "audio/x-mp3",
# WAV & AIFF (Âm thanh không nén chất lượng cao)
"audio/wav", "audio/x-wav", "audio/aiff", "audio/x-aiff",
# Containers thế hệ mới & Web (Ogg, WebM, Opus)
"audio/ogg", "audio/webm", "video/webm", "audio/opus",
# FLAC (Âm thanh nén không mất dữ liệu)
"audio/flac",
# AAC & M4A (Hệ sinh thái Apple / Chuẩn nén nâng cao)
"audio/m4a", "audio/x-m4a", "audio/mp4",
"audio/aac", "audio/x-aac", "audio/x-caf", "audio/vnd.dlna.adts",
# Định dạng ghi âm di động cũ / Băng thông thấp
"audio/amr", "audio/3gpp",
}
# ---------------------------------------------------------------------------
# Whisper – Speech-to-Text via HF Serverless Inference API
# ---------------------------------------------------------------------------
def transcribe_audio(audio_bytes: bytes, content_type: str = "audio/mpeg") -> str:
"""Gửi bytes âm thanh tới Hugging Face Inference API và nhận lại văn bản."""
# HF Inference API strict về content-type
hf_supported_types = {
"audio/flac", "audio/x-flac", "audio/mpeg", "audio/x-mpeg-3",
"audio/wave", "audio/wav", "audio/x-wav", "audio/ogg", "audio/x-audio",
"audio/webm", "audio/amr", "audio/AMR", "audio/m4a", "audio/x-m4a"
}
# Map AAC và các định dạng khác sang định dạng HF hỗ trợ
if content_type in ["audio/aac", "audio/x-aac", "audio/vnd.dlna.adts"]:
content_type = "audio/m4a"
elif content_type not in hf_supported_types:
content_type = "audio/mpeg"
headers = {"Content-Type": content_type}
if HF_TOKEN:
headers["Authorization"] = f"Bearer {HF_TOKEN}"
response = requests.post(HF_API_URL, headers=headers, data=audio_bytes, timeout=60)
if response.status_code == 503:
# Model đang được load lên GPU, thử lại 1 lần
import time
wait_time = response.json().get("estimated_time", 20)
time.sleep(min(wait_time, 30))
response = requests.post(HF_API_URL, headers=headers, data=audio_bytes, timeout=60)
if response.status_code != 200:
raise HTTPException(
status_code=502,
detail=f"Whisper API error ({response.status_code}): {response.text}",
)
result = response.json()
return result.get("text", "").strip()
# ---------------------------------------------------------------------------
# Vietnamese Task Parser
# ---------------------------------------------------------------------------
# Tiền tố cần loại bỏ (prefix)
_PREFIX_PATTERNS = [
r"^(?:hãy\s+)?nhắc\s+(?:nhở\s+)?(?:tôi|tao|mình|em|anh|chị)?\s*",
r"^(?:hãy\s+)?tạo\s+(?:task|công\s+việc|nhiệm\s+vụ|nhắc\s+nhở)\s*",
r"^(?:hãy\s+)?thêm\s+(?:task|công\s+việc|nhiệm\s+vụ|nhắc\s+nhở)\s*",
r"^(?:hãy\s+)?ghi\s+(?:nhớ|chú)\s*",
r"^(?:hãy\s+)?nhớ\s+(?:là\s+)?",
]
# Từ khóa ngày tương đối
_RELATIVE_DAY_MAP = {
"hôm nay": 0,
"hôm này": 0,
"bữa nay": 0,
"nay": 0,
"ngày mai": 1,
"mai": 1,
"ngày mốt": 2,
"mốt": 2,
"ngày kia": 3,
}
# Cụm từ kết hợp buổi + ngày: "tối nay", "chiều mai", "sáng mốt"...
_COMPOUND_PERIOD_DAY = [
# (regex, period_name, day_delta)
# Sắp xếp dài trước ngắn để ưu tiên match chính xác
(r"tối\s+nay", "tối", 0),
(r"đêm\s+nay", "đêm", 0),
(r"chiều\s+nay", "chiều", 0),
(r"trưa\s+nay", "trưa", 0),
(r"sáng\s+nay", "sáng", 0),
(r"sáng\s+mai", "sáng", 1),
(r"chiều\s+mai", "chiều", 1),
(r"tối\s+mai", "tối", 1),
(r"đêm\s+mai", "đêm", 1),
(r"trưa\s+mai", "trưa", 1),
(r"sáng\s+mốt", "sáng", 2),
(r"chiều\s+mốt", "chiều", 2),
(r"tối\s+mốt", "tối", 2),
]
# Thứ trong tuần
_WEEKDAY_MAP = {
"thứ hai": 0, "thứ 2": 0,
"thứ ba": 1, "thứ 3": 1,
"thứ tư": 2, "thứ 4": 2,
"thứ năm": 3, "thứ 5": 3,
"thứ sáu": 4, "thứ 6": 4,
"thứ bảy": 5, "thứ 7": 5,
"chủ nhật": 6, "cn": 6,
}
# Buổi -> giờ mặc định
_PERIOD_HOUR_OFFSET = {
"sáng": 0,
"trưa": 0,
"chiều": 12,
"tối": 12,
"đêm": 12,
}
# Giờ mặc định cho buổi khi không nói giờ cụ thể
_PERIOD_DEFAULT_HOUR = {
"sáng": 8,
"trưa": 12,
"chiều": 14,
"tối": 20,
"đêm": 22,
}
def _now_vn() -> datetime:
"""Trả về thời gian hiện tại theo UTC+7."""
from datetime import timezone
vn_tz = timezone(timedelta(hours=7))
return datetime.now(vn_tz)
def _strip_prefix(text: str) -> str:
"""Loại bỏ các tiền tố thừa như 'nhắc tôi', 'tạo task'..."""
cleaned = text.strip()
for pattern in _PREFIX_PATTERNS:
cleaned = re.sub(pattern, "", cleaned, flags=re.IGNORECASE).strip()
return cleaned
def _parse_date(text: str, now: datetime) -> tuple[Optional[datetime], str, str, Optional[str]]:
"""
Trích xuất ngày từ văn bản tiếng Việt.
Trả về (date_obj, matched_text, remaining_text, detected_period).
detected_period là buổi (sáng/chiều/tối...) nếu tìm thấy cụm "tối nay", "chiều mai"...
"""
lower = text.lower()
# 0. Cụm kết hợp buổi + ngày: "tối nay", "chiều mai", "sáng mốt"...
for pattern, period, delta in _COMPOUND_PERIOD_DAY:
m = re.search(pattern, lower)
if m:
dt = (now + timedelta(days=delta)).replace(
hour=0, minute=0, second=0, microsecond=0
)
remaining = text[:m.start()] + text[m.end():]
return dt, m.group(0), remaining.strip(), period
# 1. Ngày cụ thể DD/MM hoặc DD-MM hoặc DD/MM/YYYY
date_match = re.search(
r"(?:ngày\s+)?(\d{1,2})\s*[/-]\s*(\d{1,2})(?:\s*[/-]\s*(\d{4}))?", lower
)
if date_match:
day = int(date_match.group(1))
month = int(date_match.group(2))
year = int(date_match.group(3)) if date_match.group(3) else now.year
try:
dt = now.replace(year=year, month=month, day=day, hour=0, minute=0, second=0, microsecond=0)
remaining = text[:date_match.start()] + text[date_match.end():]
return dt, date_match.group(0), remaining.strip(), None
except ValueError:
pass
# 2. Thứ trong tuần
for name, weekday in _WEEKDAY_MAP.items():
idx = lower.find(name)
if idx != -1:
days_ahead = weekday - now.weekday()
if days_ahead <= 0:
days_ahead += 7
dt = (now + timedelta(days=days_ahead)).replace(
hour=0, minute=0, second=0, microsecond=0
)
remaining = text[:idx] + text[idx + len(name):]
return dt, name, remaining.strip(), None
# 3. Ngày tương đối
for name, delta in sorted(_RELATIVE_DAY_MAP.items(), key=lambda x: -len(x[0])):
idx = lower.find(name)
if idx != -1:
dt = (now + timedelta(days=delta)).replace(
hour=0, minute=0, second=0, microsecond=0
)
remaining = text[:idx] + text[idx + len(name):]
return dt, name, remaining.strip(), None
# Mặc định: hôm nay
return now.replace(hour=0, minute=0, second=0, microsecond=0), "", text, None
def _parse_time(text: str, detected_period: Optional[str] = None) -> tuple[Optional[int], Optional[int], str, str]:
"""
Trích xuất giờ/phút từ văn bản.
detected_period: buổi đã được nhận từ _parse_date (ví dụ "tối" trong "tối nay").
Trả về (hour, minute, matched_text, remaining_text).
"""
lower = text.lower()
# Pattern: "lúc X giờ Y phút" / "X giờ Y" / "Xh Y" / "XhY" / "lúc X giờ"
# Bao gồm hỗ trợ "rưỡi" (= :30) và "kém X" (= 60-X phút)
periods_alt = "|".join(_PERIOD_HOUR_OFFSET.keys())
time_patterns = [
# "lúc 2 giờ rưỡi chiều" / "8h rưỡi" / "8 giờ rưỡi"
r"(?:lúc\s+|vào\s+)?(\d{1,2})\s*(?:giờ|h|:)\s*(rưỡi)\s*(?:(" + periods_alt + r"))?",
# "lúc 2 giờ 30 phút chiều" / "lúc 2 giờ 30 chiều" / "8h30"
r"(?:lúc\s+|vào\s+)?(\d{1,2})\s*(?:giờ|h|:)\s*(\d{1,2})\s*(?:phút\s*)?(?:(" + periods_alt + r"))?",
# "lúc 2 giờ chiều" / "8h tối" / "lúc 8 giờ"
r"(?:lúc\s+|vào\s+)?(\d{1,2})\s*(?:giờ|h)\s*(?:(" + periods_alt + r"))?",
]
for pattern in time_patterns:
m = re.search(pattern, lower)
if m:
groups = m.groups()
hour = int(groups[0])
# Xác định minute
if len(groups) >= 2 and groups[1]:
if groups[1] == "rưỡi":
minute = 30
elif groups[1].isdigit():
minute = int(groups[1])
else:
minute = 0
else:
minute = 0
# Xác định period (buổi) - từ regex hoặc từ _parse_date
period = None
for g in groups[1:]:
if g and g in _PERIOD_HOUR_OFFSET:
period = g
break
if not period and detected_period:
period = detected_period
# Áp dụng offset buổi
if period and period in _PERIOD_HOUR_OFFSET:
if hour <= 12 and _PERIOD_HOUR_OFFSET[period] == 12:
if hour != 12:
hour += 12
elif period == "sáng" and hour == 12:
hour = 0
remaining = text[:m.start()] + text[m.end():]
return hour, minute, m.group(0), remaining.strip()
# Nếu không có giờ cụ thể nhưng có buổi từ compound ("tối nay" → 20:00)
if detected_period and detected_period in _PERIOD_DEFAULT_HOUR:
return _PERIOD_DEFAULT_HOUR[detected_period], 0, detected_period, text
# Pattern chỉ có buổi đứng riêng: "chiều", "tối"
for period_name, default_hour in _PERIOD_DEFAULT_HOUR.items():
idx = lower.find(period_name)
if idx != -1:
remaining = text[:idx] + text[idx + len(period_name):]
return default_hour, 0, period_name, remaining.strip()
return None, None, "", text
_NUMBER_WORDS_VI = {
"1": "Một", "2": "Hai", "3": "Ba", "4": "Bốn", "5": "Năm",
"6": "Sáu", "7": "Bảy", "8": "Tám", "9": "Chín", "10": "Mười",
}
def _number_to_word(match: re.Match) -> str:
"""Chuyển số ở đầu câu thành chữ tiếng Việt: '1 cuộc họp' → 'Một cuộc họp'."""
num = match.group(1)
word = _NUMBER_WORDS_VI.get(num, num)
return word + " "
def _clean_task_title(text: str) -> str:
"""Dọn dẹp nội dung task title sau khi đã trích xuất ngày giờ."""
# Loại bỏ các từ nối / đệm thừa ở đầu
cleaned = re.sub(
r"^\s*(?:là|để|về|cho|rằng|vào|lúc|khi|thì|mà|có|tôi\s+có|tôi\s+cần|tôi\s+phải)\s+",
"", text, flags=re.IGNORECASE
)
# Loại bỏ từ thừa ở cuối
cleaned = re.sub(r"\s+(?:vào|lúc|khi|nha|nhé|nè|đi|á|ạ)\s*$", "", cleaned, flags=re.IGNORECASE)
# Loại bỏ đại từ nhân xưng + "có/cần/phải" thừa ở đầu: "tôi có 1 cuộc họp" → "1 cuộc họp"
cleaned = re.sub(
r"^\s*(?:tôi|tao|mình|em|anh|chị)\s+(?:có|cần|phải|sẽ|đi)\s+",
"", cleaned, flags=re.IGNORECASE
)
# Chuyển số đếm ở đầu câu thành chữ: "1 cuộc họp" → "Một cuộc họp"
cleaned = re.sub(r"^\s*(\d{1,2})\s+", _number_to_word, cleaned)
# Loại bỏ dấu phẩy/chấm thừa ở đầu/cuối
cleaned = cleaned.strip(" ,.\t\n")
# Viết hoa chữ cái đầu
if cleaned:
cleaned = cleaned[0].upper() + cleaned[1:]
return cleaned
def parse_vietnamese_task(text: str) -> dict:
"""
Phân tích một câu nói tiếng Việt và trích xuất thông tin Task.
Ví dụ:
"Nhắc tôi họp với đối tác lúc 2 giờ chiều mai"
→ { task_title: "Họp với đối tác", due_datetime: "2026-05-21T14:00:00+07:00" }
"""
now = _now_vn()
# Bước 1: Loại bỏ tiền tố
cleaned = _strip_prefix(text)
# Bước 2: Trích xuất ngày (+ buổi nếu có cụm "tối nay", "chiều mai"...)
date_obj, date_text, remaining, detected_period = _parse_date(cleaned, now)
# Bước 3: Trích xuất giờ (truyền detected_period để hỗ trợ quy đổi AM/PM)
hour, minute, time_text, remaining = _parse_time(remaining, detected_period)
# Bước 4: Gộp ngày + giờ
if hour is not None:
date_obj = date_obj.replace(hour=hour, minute=minute or 0)
else:
# Nếu không nói giờ cụ thể, để 09:00 làm mặc định
date_obj = date_obj.replace(hour=9, minute=0)
# Bước 5: Tạo task title
task_title = _clean_task_title(remaining)
# Tổng hợp phần text thời gian đã match
parsed_time_parts = [p for p in [date_text, time_text] if p]
parsed_time_text = " ".join(parsed_time_parts).strip()
# Đánh giá confidence dựa trên các yếu tố đã trích xuất
confidence = 0.5
if task_title:
confidence += 0.2
if date_text:
confidence += 0.15
if time_text:
confidence += 0.15
return {
"success": True,
"raw_text": text,
"task_title": task_title if task_title else text,
"due_datetime": date_obj.isoformat(),
"parsed_time_text": parsed_time_text if parsed_time_text else None,
"confidence": round(confidence, 2),
}
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@app.get("/")
def root():
return {
"service": "Remind - Voice Task Creator",
"version": "1.0.0",
"endpoints": {
"POST /api/v1/detect": "Upload file âm thanh → nhận diện giọng nói → trích xuất task (JSON)",
"POST /api/v1/parse": "Gửi văn bản tiếng Việt để phân tích task (không cần âm thanh)",
"GET /docs": "Tài liệu API tương tác (Swagger UI)",
},
}
@app.post("/api/v1/detect")
async def detect_voice_task(file: UploadFile = File(..., description="File ghi âm (.mp3, .wav, .m4a, .ogg, .webm, .aac, .flac, ...)")):
"""
Nhận file ghi âm giọng nói, chuyển thành văn bản bằng Whisper,
sau đó phân tích và trích xuất thông tin Task tiếng Việt.
"""
# Kiểm tra loại file
content_type = file.content_type or ""
if content_type and content_type not in ALLOWED_AUDIO_TYPES:
raise HTTPException(
status_code=400,
detail=f"Loại file không được hỗ trợ: {content_type}. "
f"Vui lòng upload file âm thanh (.mp3, .wav, .m4a, .ogg, .webm, .aac, .flac, ...).",
)
# Đọc nội dung file
audio_bytes = await file.read()
if len(audio_bytes) == 0:
raise HTTPException(status_code=400, detail="File âm thanh rỗng.")
if len(audio_bytes) > 25 * 1024 * 1024: # 25 MB limit
raise HTTPException(status_code=400, detail="File quá lớn. Giới hạn 25MB.")
# Bước 1: Speech-to-Text bằng Whisper
audio_content_type = file.content_type or "audio/mpeg"
transcribed_text = transcribe_audio(audio_bytes, audio_content_type)
if not transcribed_text:
return {
"success": False,
"error": "Không nhận diện được giọng nói. Vui lòng thử lại với bản ghi rõ hơn.",
"raw_text": "",
"task_title": None,
"due_datetime": None,
"parsed_time_text": None,
"confidence": 0.0,
}
# Bước 2: Phân tích task từ văn bản
result = parse_vietnamese_task(transcribed_text)
return result
@app.post("/api/v1/parse")
def parse_text(text: str):
"""
Endpoint phụ trợ: Nhận văn bản tiếng Việt trực tiếp (không cần file âm thanh)
và trả về kết quả phân tích Task.
Hữu ích để test bộ parser mà không cần ghi âm.
"""
if not text or not text.strip():
raise HTTPException(status_code=400, detail="Văn bản không được để trống.")
return parse_vietnamese_task(text.strip())