feat: 足球 LLM 预测服务初始提交
Profeto — 给 LLM 提供数据,让 LLM 预测足球比分。 核心模块: - FastAPI 后端 + PostgreSQL (SQLAlchemy async) - 多 Agent LLM 预测 (5 专家 + 终裁) - 数据采集 (bzzoiro / understat / injuries) - React 前端 (Vite + Tailwind) 包含: - 数据源抽象 (DataSource 协议 + 注册表) - Alembic 数据库迁移 - Prompt 模板 (单/多 Agent) - 核心路径单元测试
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
"""SQLAlchemy async engine + session。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from src.core.config import settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.DATABASE_URL,
|
||||
echo=False,
|
||||
pool_pre_ping=True,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncIterator[AsyncSession]:
|
||||
"""写路由用: 退出时自动 commit。"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
async def get_db_read() -> AsyncIterator[AsyncSession]:
|
||||
"""读路由用: 不 commit(只读)。"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
"""开发/测试用:建表。生产建议用 alembic。"""
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
@@ -0,0 +1,175 @@
|
||||
"""5 张表 ORM: leagues / teams / matches / match_stats / predictions。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
Date,
|
||||
DateTime,
|
||||
Float,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from src.db.base import Base
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class League(Base):
|
||||
__tablename__ = "leagues"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(20), unique=True, nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
country: Mapped[str | None] = mapped_column(String(50))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
||||
|
||||
matches: Mapped[list["Match"]] = relationship(back_populates="league")
|
||||
|
||||
|
||||
class Team(Base):
|
||||
__tablename__ = "teams"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(120), unique=True, nullable=False)
|
||||
name_zh: Mapped[str | None] = mapped_column(String(60))
|
||||
team_type: Mapped[str] = mapped_column(String(20), default="club")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
||||
|
||||
home_matches: Mapped[list["Match"]] = relationship(foreign_keys="Match.home_team_id", back_populates="home_team")
|
||||
away_matches: Mapped[list["Match"]] = relationship(foreign_keys="Match.away_team_id", back_populates="away_team")
|
||||
|
||||
|
||||
class Match(Base):
|
||||
__tablename__ = "matches"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
league_id: Mapped[int] = mapped_column(ForeignKey("leagues.id"), nullable=False)
|
||||
season: Mapped[str | None] = mapped_column(String(12))
|
||||
home_team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), nullable=False)
|
||||
away_team_id: Mapped[int] = mapped_column(ForeignKey("teams.id"), nullable=False)
|
||||
match_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
match_date_date: Mapped[date] = mapped_column(
|
||||
"match_date_date",
|
||||
Date,
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
match_status: Mapped[str] = mapped_column(String(20), default="scheduled")
|
||||
home_goals: Mapped[int | None] = mapped_column(Integer)
|
||||
away_goals: Mapped[int | None] = mapped_column(Integer)
|
||||
home_ht_goals: Mapped[int | None] = mapped_column(Integer)
|
||||
away_ht_goals: Mapped[int | None] = mapped_column(Integer)
|
||||
match_stage: Mapped[str | None] = mapped_column(String(100))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
|
||||
|
||||
league: Mapped[League] = relationship(back_populates="matches")
|
||||
home_team: Mapped[Team] = relationship(foreign_keys=[home_team_id], back_populates="home_matches")
|
||||
away_team: Mapped[Team] = relationship(foreign_keys=[away_team_id], back_populates="away_matches")
|
||||
stats: Mapped["MatchStats | None"] = relationship(back_populates="match", cascade="all, delete-orphan")
|
||||
predictions: Mapped[list["Prediction"]] = relationship(back_populates="match", cascade="all, delete-orphan")
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_matches_league_date", "league_id", match_date.desc()),
|
||||
Index("ix_matches_home_date", "home_team_id", match_date.desc()),
|
||||
Index("ix_matches_away_date", "away_team_id", match_date.desc()),
|
||||
Index("ix_matches_status_date", "match_status", match_date.desc()),
|
||||
Index(
|
||||
"ix_matches_unique",
|
||||
"league_id",
|
||||
"home_team_id",
|
||||
"away_team_id",
|
||||
"match_date_date",
|
||||
unique=True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class MatchStats(Base):
|
||||
__tablename__ = "match_stats"
|
||||
|
||||
match_id: Mapped[int] = mapped_column(ForeignKey("matches.id", ondelete="CASCADE"), primary_key=True)
|
||||
home_xg: Mapped[float | None] = mapped_column(Float)
|
||||
away_xg: Mapped[float | None] = mapped_column(Float)
|
||||
home_shots: Mapped[int | None] = mapped_column(Integer)
|
||||
away_shots: Mapped[int | None] = mapped_column(Integer)
|
||||
home_shots_on_target: Mapped[int | None] = mapped_column(Integer)
|
||||
away_shots_on_target: Mapped[int | None] = mapped_column(Integer)
|
||||
home_corners: Mapped[int | None] = mapped_column(Integer)
|
||||
away_corners: Mapped[int | None] = mapped_column(Integer)
|
||||
home_possession: Mapped[float | None] = mapped_column(Float)
|
||||
home_yellow_cards: Mapped[int | None] = mapped_column(Integer)
|
||||
away_yellow_cards: Mapped[int | None] = mapped_column(Integer)
|
||||
home_red_cards: Mapped[int | None] = mapped_column(Integer)
|
||||
away_red_cards: Mapped[int | None] = mapped_column(Integer)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
|
||||
|
||||
match: Mapped[Match] = relationship(back_populates="stats")
|
||||
|
||||
|
||||
class Injury(Base):
|
||||
"""球员伤停记录(api-football 数据源)。"""
|
||||
__tablename__ = "injuries"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
player_id: Mapped[int | None] = mapped_column(Integer, index=True)
|
||||
player_name: Mapped[str] = mapped_column(String(120), nullable=False)
|
||||
team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id"), index=True)
|
||||
fixture_id: Mapped[int | None] = mapped_column(Integer)
|
||||
league_id: Mapped[int | None] = mapped_column(Integer)
|
||||
injury_type: Mapped[str | None] = mapped_column(String(50)) # Missing Fixture / Suspended
|
||||
reason: Mapped[str | None] = mapped_column(String(200))
|
||||
injury_date: Mapped[date | None] = mapped_column(Date, index=True)
|
||||
return_date: Mapped[date | None] = mapped_column(Date)
|
||||
retrieved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
||||
|
||||
team: Mapped["Team | None"] = relationship()
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_injuries_player_fixture", "player_id", "fixture_id", "injury_type", unique=True),
|
||||
Index("ix_injuries_team_date", "team_id", "injury_date"),
|
||||
)
|
||||
|
||||
|
||||
class Prediction(Base):
|
||||
__tablename__ = "predictions"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
match_id: Mapped[int] = mapped_column(ForeignKey("matches.id"), nullable=False)
|
||||
provider: Mapped[str] = mapped_column(String(30), nullable=False)
|
||||
model: Mapped[str] = mapped_column(String(80), nullable=False)
|
||||
prompt_version: Mapped[str] = mapped_column(String(20), nullable=False, default="v1")
|
||||
prompt_tokens: Mapped[int | None] = mapped_column(Integer)
|
||||
completion_tokens: Mapped[int | None] = mapped_column(Integer)
|
||||
latency_ms: Mapped[int | None] = mapped_column(Integer)
|
||||
pred_home_goals: Mapped[float | None] = mapped_column(Float)
|
||||
pred_away_goals: Mapped[float | None] = mapped_column(Float)
|
||||
pred_1x2: Mapped[str | None] = mapped_column(String(3))
|
||||
confidence: Mapped[float | None] = mapped_column(Float)
|
||||
reasoning: Mapped[str | None] = mapped_column(Text)
|
||||
raw_response: Mapped[dict | None] = mapped_column(JSONB)
|
||||
# multi-agent 模式: 各专家报告
|
||||
mode: Mapped[str] = mapped_column(String(20), nullable=False, default="single")
|
||||
agent_outputs: Mapped[dict | None] = mapped_column(JSONB)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow)
|
||||
actual_home_goals: Mapped[int | None] = mapped_column(Integer)
|
||||
actual_away_goals: Mapped[int | None] = mapped_column(Integer)
|
||||
settled: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
match: Mapped[Match] = relationship(back_populates="predictions")
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_predictions_match", "match_id"),
|
||||
Index("ix_predictions_provider_model", "provider", "model"),
|
||||
)
|
||||
Reference in New Issue
Block a user