Initial speaking practice site

This commit is contained in:
TTlaji committed 2026-06-03 00:34:42 +08:00
commit bcebeaef82
38 files changed
+10698

No files matched your search

+1
View File
@@ -0,0 +1 @@
+396
View File
@@ -0,0 +1,396 @@
from pathlib import Path
import json
import sqlite3
BASE_DIR = Path(__file__).resolve().parent
DATABASE_PATH = BASE_DIR / "speaking_lab.sqlite"
MOJIBAKE_MARKERS = ("Ã", "Â", "â", "ä", "å", "æ", "ç", "è", "é")
def get_connection() -> sqlite3.Connection:
connection = sqlite3.connect(DATABASE_PATH)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys = ON")
return connection
def initialize_database() -> None:
BASE_DIR.mkdir(parents=True, exist_ok=True)
with get_connection() as connection:
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
display_name TEXT,
role TEXT NOT NULL DEFAULT 'user',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
speaker TEXT,
description TEXT,
tags TEXT,
video_url TEXT,
duration_seconds INTEGER,
status TEXT NOT NULL DEFAULT 'draft',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS subtitles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL,
language_code TEXT NOT NULL,
language_name TEXT,
format TEXT NOT NULL,
file_path TEXT,
content TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (video_id) REFERENCES videos (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS user_interactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
video_id INTEGER NOT NULL,
interaction_type TEXT NOT NULL,
current_time_ms INTEGER,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, video_id, interaction_type),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (video_id) REFERENCES videos (id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_videos_title ON videos (title);
CREATE INDEX IF NOT EXISTS idx_subtitles_video_id ON subtitles (video_id);
CREATE INDEX IF NOT EXISTS idx_user_interactions_user_id
ON user_interactions (user_id);
"""
)
connection.execute(
"""
DELETE FROM subtitles
WHERE id NOT IN (
SELECT MAX(id)
FROM subtitles
GROUP BY video_id, language_code
)
"""
)
connection.execute(
"""
CREATE UNIQUE INDEX IF NOT EXISTS idx_subtitles_video_language
ON subtitles (video_id, language_code)
"""
)
def repair_mojibake_text(value: str | None) -> str:
if not value:
return ""
repaired = value
for _ in range(2):
if not any(marker in repaired for marker in MOJIBAKE_MARKERS):
break
try:
candidate = repaired.encode("latin1").decode("utf-8")
except UnicodeError:
break
if candidate == repaired:
break
repaired = candidate
return repaired
def parse_tags(tags_text: str | None) -> list[str]:
tags = [
tag.strip()
for tag in repair_mojibake_text(tags_text).replace(",", ",").split(",")
if tag.strip()
]
return tags or ["未分类"]
def row_to_video(row: sqlite3.Row, subtitle_rows: list[sqlite3.Row]) -> dict[str, object]:
subtitles: dict[str, dict[str, str]] = {}
for subtitle in subtitle_rows:
subtitles[subtitle["language_code"]] = {
"languageName": repair_mojibake_text(subtitle["language_name"] or subtitle["language_code"]),
"format": subtitle["format"],
"filePath": subtitle["file_path"],
"content": repair_mojibake_text(subtitle["content"] or ""),
}
try:
tags = json.loads(row["tags"] or "[]")
except json.JSONDecodeError:
tags = parse_tags(row["tags"])
tags = [repair_mojibake_text(str(tag)) for tag in tags] if isinstance(tags, list) else parse_tags(str(tags))
return {
"id": row["id"],
"title": repair_mojibake_text(row["title"]),
"speaker": repair_mojibake_text(row["speaker"] or "Unknown"),
"description": repair_mojibake_text(row["description"] or ""),
"tags": tags if isinstance(tags, list) and tags else ["未分类"],
"duration": row["duration_seconds"] or 0,
"videoUrl": row["video_url"] or "",
"sourceType": "url" if str(row["video_url"] or "").startswith(("http://", "https://")) else "local-file",
"subtitles": subtitles,
}
def create_video(
*,
title: str,
speaker: str | None,
description: str | None,
tags: list[str],
video_url: str,
subtitles: list[dict[str, str]],
) -> dict[str, object]:
with get_connection() as connection:
cursor = connection.execute(
"""
INSERT INTO videos (
title, speaker, description, tags, video_url, status
)
VALUES (?, ?, ?, ?, ?, 'published')
""",
(
title,
repair_mojibake_text(speaker or "Unknown"),
repair_mojibake_text(description or ""),
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
repair_mojibake_text(video_url),
),
)
video_id = int(cursor.lastrowid)
for subtitle in subtitles:
connection.execute(
"""
INSERT INTO subtitles (
video_id, language_code, language_name, format, file_path, content
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
video_id,
subtitle["language_code"],
repair_mojibake_text(subtitle["language_name"]),
subtitle["format"],
subtitle["file_path"],
repair_mojibake_text(subtitle["content"]),
),
)
video = get_video(video_id)
if video is None:
raise RuntimeError("Created video could not be loaded")
return video
def list_videos() -> list[dict[str, object]]:
with get_connection() as connection:
video_rows = connection.execute(
"""
SELECT *
FROM videos
WHERE status = 'published'
ORDER BY created_at DESC, id DESC
"""
).fetchall()
subtitle_rows = connection.execute(
"""
SELECT *
FROM subtitles
ORDER BY id ASC
"""
).fetchall()
subtitles_by_video: dict[int, list[sqlite3.Row]] = {}
for subtitle in subtitle_rows:
subtitles_by_video.setdefault(int(subtitle["video_id"]), []).append(subtitle)
return [
row_to_video(row, subtitles_by_video.get(int(row["id"]), []))
for row in video_rows
]
def get_video(video_id: int) -> dict[str, object] | None:
with get_connection() as connection:
row = connection.execute(
"""
SELECT *
FROM videos
WHERE id = ? AND status = 'published'
""",
(video_id,),
).fetchone()
if row is None:
return None
subtitle_rows = connection.execute(
"""
SELECT *
FROM subtitles
WHERE video_id = ?
ORDER BY id ASC
""",
(video_id,),
).fetchall()
return row_to_video(row, subtitle_rows)
def delete_video(video_id: int) -> dict[str, object] | None:
with get_connection() as connection:
video_row = connection.execute(
"""
SELECT id, video_url
FROM videos
WHERE id = ?
""",
(video_id,),
).fetchone()
if video_row is None:
return None
subtitle_rows = connection.execute(
"""
SELECT file_path
FROM subtitles
WHERE video_id = ?
""",
(video_id,),
).fetchall()
upload_paths = []
if video_row["video_url"]:
upload_paths.append(video_row["video_url"])
upload_paths.extend(row["file_path"] for row in subtitle_rows if row["file_path"])
connection.execute("DELETE FROM videos WHERE id = ?", (video_id,))
return {
"deletedVideoId": video_id,
"uploadPaths": upload_paths,
}
def update_video(
video_id: int,
*,
title: str,
speaker: str | None,
description: str | None,
tags: list[str],
video_url: str | None,
subtitles: list[dict[str, str]],
) -> dict[str, object] | None:
with get_connection() as connection:
existing = connection.execute(
"""
SELECT id, video_url
FROM videos
WHERE id = ?
""",
(video_id,),
).fetchone()
if existing is None:
return None
old_upload_paths = []
final_video_url = video_url if video_url is not None else existing["video_url"]
if video_url is not None and existing["video_url"] and existing["video_url"] != video_url:
old_upload_paths.append(existing["video_url"])
connection.execute(
"""
UPDATE videos
SET title = ?,
speaker = ?,
description = ?,
tags = ?,
video_url = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""",
(
title,
repair_mojibake_text(speaker or "Unknown"),
repair_mojibake_text(description or ""),
json.dumps([repair_mojibake_text(tag) for tag in tags], ensure_ascii=False),
repair_mojibake_text(final_video_url),
video_id,
),
)
for subtitle in subtitles:
existing_subtitle = connection.execute(
"""
SELECT file_path
FROM subtitles
WHERE video_id = ? AND language_code = ?
""",
(video_id, subtitle["language_code"]),
).fetchone()
if existing_subtitle and existing_subtitle["file_path"] != subtitle["file_path"]:
old_upload_paths.append(existing_subtitle["file_path"])
connection.execute(
"""
INSERT INTO subtitles (
video_id, language_code, language_name, format, file_path, content
)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(video_id, language_code) DO UPDATE SET
language_name = excluded.language_name,
format = excluded.format,
file_path = excluded.file_path,
content = excluded.content,
updated_at = CURRENT_TIMESTAMP
""",
(
video_id,
subtitle["language_code"],
repair_mojibake_text(subtitle["language_name"]),
subtitle["format"],
subtitle["file_path"],
repair_mojibake_text(subtitle["content"]),
),
)
video = get_video(video_id)
if video is None:
return None
return {
"video": video,
"oldUploadPaths": old_upload_paths,
}
def table_names() -> list[str]:
with get_connection() as connection:
rows = connection.execute(
"""
SELECT name
FROM sqlite_master
WHERE type = 'table'
AND name NOT LIKE 'sqlite_%'
ORDER BY name
"""
).fetchall()
return [row["name"] for row in rows]
+356
View File
@@ -0,0 +1,356 @@
from pathlib import Path
from urllib.parse import urlparse
from uuid import uuid4
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from .db import (
DATABASE_PATH,
create_video,
delete_video,
initialize_database,
list_videos,
parse_tags,
table_names,
get_video,
update_video,
)
PROJECT_DIR = Path(__file__).resolve().parent.parent
UPLOADS_DIR = PROJECT_DIR / "uploads"
VIDEO_EXTENSIONS = {".mp4", ".webm", ".mov", ".m4v"}
SUBTITLE_EXTENSIONS = {".srt", ".vtt"}
UPLOAD_CHUNK_SIZE = 1024 * 1024
def ensure_upload_directories() -> None:
UPLOADS_DIR.mkdir(parents=True, exist_ok=True)
(UPLOADS_DIR / "videos").mkdir(parents=True, exist_ok=True)
(UPLOADS_DIR / "subtitles").mkdir(parents=True, exist_ok=True)
def extension_for_upload(upload: UploadFile) -> str:
return Path(upload.filename or "").suffix.lower()
def safe_upload_name(upload: UploadFile) -> str:
extension = extension_for_upload(upload)
return f"{uuid4().hex}{extension}"
async def save_upload(upload: UploadFile, target_dir: Path) -> tuple[str, str]:
target_dir.mkdir(parents=True, exist_ok=True)
filename = safe_upload_name(upload)
target_path = target_dir / filename
content = await upload.read()
try:
target_path.write_bytes(content)
except OSError as exc:
target_path.unlink(missing_ok=True)
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
return filename, content.decode("utf-8-sig", errors="replace")
async def save_binary_upload(upload: UploadFile, target_dir: Path) -> str:
target_dir.mkdir(parents=True, exist_ok=True)
filename = safe_upload_name(upload)
target_path = target_dir / filename
try:
with target_path.open("wb") as target_file:
while chunk := await upload.read(UPLOAD_CHUNK_SIZE):
target_file.write(chunk)
except OSError as exc:
target_path.unlink(missing_ok=True)
raise HTTPException(status_code=500, detail="保存文件失败,请重试") from exc
return filename
def cleanup_saved_files(paths: list[Path]) -> None:
for path in paths:
try:
path.unlink(missing_ok=True)
except OSError:
pass
def upload_url_to_path(value: str) -> Path | None:
if not value.startswith("/uploads/"):
return None
relative_parts = value.removeprefix("/uploads/").split("/")
if any(part in {"", ".", ".."} for part in relative_parts):
return None
candidate = (UPLOADS_DIR / Path(*relative_parts)).resolve()
uploads_root = UPLOADS_DIR.resolve()
try:
candidate.relative_to(uploads_root)
except ValueError:
return None
return candidate
def is_supported_video_url(value: str) -> bool:
parsed = urlparse(value)
return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
def cleanup_upload_urls(upload_urls: list[str]) -> list[str]:
warnings: list[str] = []
for upload_url in upload_urls:
path = upload_url_to_path(str(upload_url))
if path is None:
continue
try:
path.unlink(missing_ok=True)
except OSError:
warnings.append(f"无法删除文件: {path}")
return warnings
ensure_upload_directories()
app = FastAPI(title="Speaking Lab API")
@app.on_event("startup")
def on_startup() -> None:
initialize_database()
ensure_upload_directories()
app.mount("/uploads", StaticFiles(directory=UPLOADS_DIR), name="uploads")
@app.get("/api/health")
def health_check() -> dict[str, object]:
return {
"ok": True,
"database": str(DATABASE_PATH),
"tables": table_names(),
}
@app.get("/api/videos")
def api_list_videos() -> list[dict[str, object]]:
return list_videos()
@app.get("/api/videos/{video_id}")
def api_get_video(video_id: int) -> dict[str, object]:
video = get_video(video_id)
if video is None:
raise HTTPException(status_code=404, detail="视频不存在")
return video
@app.post("/api/videos")
async def api_create_video(
title: str = Form(...),
speaker: str = Form(""),
description: str = Form(""),
tags: str = Form(""),
video_url: str = Form(""),
video_file: UploadFile | None = File(None),
subtitle_en: UploadFile | None = File(None),
subtitle_zh: UploadFile | None = File(None),
) -> dict[str, object]:
clean_title = title.strip()
if not clean_title:
raise HTTPException(status_code=400, detail="标题不能为空")
clean_video_url = video_url.strip()
if video_file is None and not clean_video_url:
raise HTTPException(status_code=400, detail="请上传视频文件或填写视频地址")
if video_file is None and not is_supported_video_url(clean_video_url):
raise HTTPException(status_code=400, detail="视频地址必须以 http:// 或 https:// 开头")
if video_file is not None:
if extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
raise HTTPException(status_code=400, detail="视频文件格式不支持")
subtitle_uploads: list[tuple[UploadFile, str, str, str]] = []
for upload, language_code, language_name in (
(subtitle_en, "en", "English"),
(subtitle_zh, "zh", "中文"),
):
if upload is None:
continue
extension = extension_for_upload(upload)
if extension not in SUBTITLE_EXTENSIONS:
raise HTTPException(status_code=400, detail="字幕只支持 .srt 或 .vtt")
subtitle_uploads.append((upload, language_code, language_name, extension))
saved_paths: list[Path] = []
try:
final_video_url = clean_video_url
if video_file is not None:
video_filename = await save_binary_upload(video_file, UPLOADS_DIR / "videos")
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
final_video_url = f"/uploads/videos/{video_filename}"
subtitles: list[dict[str, str]] = []
for upload, language_code, language_name, extension in subtitle_uploads:
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
saved_paths.append(UPLOADS_DIR / "subtitles" / subtitle_filename)
subtitles.append(
{
"language_code": language_code,
"language_name": language_name,
"format": extension.removeprefix("."),
"file_path": f"/uploads/subtitles/{subtitle_filename}",
"content": subtitle_text,
}
)
return create_video(
title=clean_title,
speaker=speaker.strip(),
description=description.strip(),
tags=parse_tags(tags),
video_url=final_video_url,
subtitles=subtitles,
)
except Exception:
cleanup_saved_files(saved_paths)
raise
@app.patch("/api/videos/{video_id}")
async def api_update_video(
video_id: int,
title: str = Form(...),
speaker: str = Form(""),
description: str = Form(""),
tags: str = Form(""),
video_url: str = Form(""),
subtitle_en_content: str | None = Form(None),
subtitle_zh_content: str | None = Form(None),
video_file: UploadFile | None = File(None),
subtitle_en: UploadFile | None = File(None),
subtitle_zh: UploadFile | None = File(None),
) -> dict[str, object]:
existing = get_video(video_id)
if existing is None:
raise HTTPException(status_code=404, detail="视频不存在")
clean_title = title.strip()
if not clean_title:
raise HTTPException(status_code=400, detail="标题不能为空")
clean_video_url = video_url.strip()
final_video_url: str | None = None
if video_file is None and clean_video_url:
if not is_supported_video_url(clean_video_url) and not clean_video_url.startswith("/uploads/"):
raise HTTPException(status_code=400, detail="视频地址必须以 http:// 或 https:// 开头")
final_video_url = clean_video_url
if video_file is not None and extension_for_upload(video_file) not in VIDEO_EXTENSIONS:
raise HTTPException(status_code=400, detail="视频文件格式不支持")
subtitle_uploads: list[tuple[UploadFile, str, str, str]] = []
for upload, language_code, language_name in (
(subtitle_en, "en", "English"),
(subtitle_zh, "zh", "中文"),
):
if upload is None:
continue
extension = extension_for_upload(upload)
if extension not in SUBTITLE_EXTENSIONS:
raise HTTPException(status_code=400, detail="字幕只支持 .srt 或 .vtt")
subtitle_uploads.append((upload, language_code, language_name, extension))
saved_paths: list[Path] = []
try:
if video_file is not None:
video_filename = await save_binary_upload(video_file, UPLOADS_DIR / "videos")
saved_paths.append(UPLOADS_DIR / "videos" / video_filename)
final_video_url = f"/uploads/videos/{video_filename}"
subtitles: list[dict[str, str]] = []
for upload, language_code, language_name, extension in subtitle_uploads:
subtitle_filename, subtitle_text = await save_upload(upload, UPLOADS_DIR / "subtitles")
saved_paths.append(UPLOADS_DIR / "subtitles" / subtitle_filename)
subtitles.append(
{
"language_code": language_code,
"language_name": language_name,
"format": extension.removeprefix("."),
"file_path": f"/uploads/subtitles/{subtitle_filename}",
"content": subtitle_text,
}
)
uploaded_language_codes = {language_code for _, language_code, _, _ in subtitle_uploads}
existing_subtitles = existing.get("subtitles", {})
for language_code, language_name, content in (
("en", "English", subtitle_en_content),
("zh", "中文", subtitle_zh_content),
):
if content is None or language_code in uploaded_language_codes:
continue
existing_subtitle = existing_subtitles.get(language_code, {})
subtitles.append(
{
"language_code": language_code,
"language_name": existing_subtitle.get("languageName") or language_name,
"format": existing_subtitle.get("format") or "vtt",
"file_path": existing_subtitle.get("filePath") or "",
"content": content,
}
)
updated = update_video(
video_id,
title=clean_title,
speaker=speaker.strip(),
description=description.strip(),
tags=parse_tags(tags),
video_url=final_video_url,
subtitles=subtitles,
)
if updated is None:
cleanup_saved_files(saved_paths)
raise HTTPException(status_code=404, detail="视频不存在")
warnings = cleanup_upload_urls([str(path) for path in updated["oldUploadPaths"]])
return {
"ok": True,
"video": updated["video"],
"warnings": warnings,
}
except HTTPException:
cleanup_saved_files(saved_paths)
raise
except Exception:
cleanup_saved_files(saved_paths)
raise
@app.delete("/api/videos/{video_id}")
def api_delete_video(video_id: int) -> dict[str, object]:
deleted = delete_video(video_id)
if deleted is None:
raise HTTPException(status_code=404, detail="视频不存在")
warnings = cleanup_upload_urls([str(path) for path in deleted["uploadPaths"]])
return {
"ok": True,
"deletedVideoId": deleted["deletedVideoId"],
"warnings": warnings,
}
@app.get("/")
def read_index() -> FileResponse:
return FileResponse(PROJECT_DIR / "index.html")
app.mount("/", StaticFiles(directory=PROJECT_DIR), name="static")