import html
import json
import os
import re
import sqlite3
from datetime import datetime, timezone
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEFAULT_DB = os.path.join(BASE_DIR, "steam.db")
SCHEMA_PATH = os.path.join(BASE_DIR, "tools", "schema.sql")
SCHEMA_VERSION = 5
MOOD_PRESETS = {
"adventure-rpg-party": {
"description": "Приключение + RPG, прокачка героя/группы, исследование, подземелья",
"genres": ["RPG", "Adventure"],
"tags": {
"RPG": 1.0,
"Adventure": 1.0,
"Party-Based RPG": 1.3,
"Character Customization": 1.0,
"Dungeon Crawler": 1.2,
"Exploration": 1.0,
"Story Rich": 0.8,
"Turn-Based Combat": 0.7,
"CRPG": 0.9,
"Loot": 0.7,
"Choices Matter": 0.6,
"Fantasy": 0.5,
"Open World": 0.4,
},
},
"dungeon-crawler": {
"description": "Подземелья, пошаговые бои, лут, рогалик",
"genres": ["RPG", "Adventure"],
"tags": {
"Dungeon Crawler": 1.5,
"Roguelike": 1.0,
"Turn-Based Combat": 1.2,
"Loot": 1.1,
"CRPG": 0.8,
"RPG": 1.0,
"Party-Based RPG": 0.8,
"Exploration": 0.7,
},
},
"colony-management": {
"description": "Колонии, базы, менеджмент, строительство",
"genres": ["Simulation", "Strategy"],
"tags": {
"Colony Sim": 1.5,
"Base Building": 1.2,
"Management": 1.2,
"Building": 1.0,
"City Builder": 1.0,
"Resource Management": 1.0,
"Sandbox": 0.6,
"Strategy": 0.7,
"Simulation": 0.7,
},
},
"survival-craft": {
"description": "Выживание, крафт, открытый мир, кооп",
"genres": ["Action", "Adventure", "Simulation"],
"tags": {
"Survival": 1.5,
"Open World Survival Craft": 1.5,
"Crafting": 1.2,
"Base Building": 1.0,
"Exploration": 0.8,
"Open World": 0.7,
"Co-op": 0.7,
"Survival Horror": 0.4,
},
},
"story-heavy": {
"description": "Сюжет, выборы, атмосфера",
"genres": ["Adventure", "RPG"],
"tags": {
"Story Rich": 1.5,
"Narrative": 1.2,
"Choices Matter": 1.1,
"Adventure": 0.9,
"Atmospheric": 0.8,
"Exploration": 0.6,
"RPG": 0.6,
},
},
"dark-fantasy": {
"description": "Тёмное фэнтези, сложность, атмосфера",
"genres": ["RPG", "Adventure", "Action"],
"tags": {
"Dark Fantasy": 1.5,
"Souls-like": 1.2,
"Atmospheric": 1.0,
"Lore-Rich": 0.9,
"Difficult": 0.8,
"Action RPG": 0.8,
"RPG": 0.9,
"Story Rich": 0.5,
"Medieval": 0.5,
},
},
"relaxing-evening": {
"description": "Спокойный вечер: уютно и без спешки",
"genres": ["Casual", "Simulation", "Adventure"],
"tags": {
"Relaxing": 1.5,
"Cozy": 1.3,
"Farming Sim": 1.2,
"Life Sim": 0.9,
"Casual": 1.0,
"Atmospheric": 0.6,
"Building": 0.5,
"Cute": 0.5,
},
},
"coop-friends": {
"description": "Кооп с друзьями",
"genres": ["Action", "Adventure", "RPG"],
"tags": {
"Co-op": 1.5,
"Online Co-Op": 1.3,
"Multiplayer": 1.0,
"Co-op Campaign": 1.0,
"PvE": 0.8,
"Survival": 0.7,
"Open World": 0.6,
"Local Co-Op": 0.7,
},
},
"sci-fi-exploration": {
"description": "Космос, научная фантастика, исследование",
"genres": ["Adventure", "Simulation", "Action"],
"tags": {
"Sci-fi": 1.4,
"Space": 1.3,
"Exploration": 1.2,
"Open World": 0.8,
"Survival": 0.7,
"Atmospheric": 0.7,
"Cyberpunk": 0.6,
},
},
"tactical-turn-based": {
"description": "Тактика, пошаговые бои, продуманные решения",
"genres": ["Strategy", "RPG"],
"tags": {
"Turn-Based Tactics": 1.4,
"Turn-Based Combat": 1.2,
"Tactical": 1.2,
"Turn-Based Strategy": 1.0,
"Strategy": 0.9,
"RPG": 0.6,
"CRPG": 0.6,
},
},
"horror-night": {
"description": "Хоррор на ночь",
"genres": ["Adventure", "Action"],
"tags": {
"Horror": 1.5,
"Survival Horror": 1.3,
"Psychological Horror": 0.9,
"Atmospheric": 1.0,
"Dark": 0.8,
"Story Rich": 0.5,
},
},
"city-builder": {
"description": "Город, поселение, экономика, строительство",
"genres": ["Simulation", "Strategy"],
"tags": {
"City Builder": 1.5,
"Building": 1.2,
"Management": 1.1,
"Economy": 1.0,
"Resource Management": 0.9,
"Sandbox": 0.5,
"Colony Sim": 0.6,
},
},
"roguelike-run": {
"description": "Рогалик на один забег",
"genres": ["RPG", "Action", "Indie"],
"tags": {
"Roguelike": 1.4,
"Roguelite": 1.3,
"Action Roguelike": 0.9,
"Replay Value": 0.9,
"Dungeon Crawler": 0.7,
"Loot": 0.6,
},
},
"short-session": {
"description": "Короткие сессии на вечер",
"genres": ["Indie", "Casual", "Adventure"],
"tags": {
"Short": 1.5,
"Casual": 1.2,
"Relaxing": 0.8,
"Puzzle": 0.8,
"Atmospheric": 0.5,
"Story Rich": 0.5,
"Minimalist": 0.3,
},
},
"mystery-detective": {
"description": "Детектив, загадка, расследование",
"genres": ["Adventure", "RPG"],
"tags": {
"Mystery": 1.5,
"Detective": 1.4,
"Story Rich": 1.0,
"Point & Click": 0.8,
"Visual Novel": 0.7,
"Atmospheric": 0.6,
"Puzzle": 0.5,
},
},
"soulslike-challenge": {
"description": "Souls-like, сложные бои, тёмное фэнтези",
"genres": ["Action", "RPG"],
"tags": {
"Souls-like": 1.6,
"Difficult": 1.2,
"Dark Fantasy": 1.1,
"Combat": 0.8,
"Lore-Rich": 0.7,
"Action RPG": 0.8,
},
},
"cozy-coop": {
"description": "Уютный кооп: ферма, готовка, спокойствие",
"genres": ["Simulation", "Casual", "Adventure"],
"tags": {
"Cozy": 1.5,
"Co-op": 1.3,
"Farming Sim": 1.1,
"Relaxing": 1.0,
"Cute": 0.7,
"Building": 0.6,
},
},
"deckbuilder": {
"description": "Колодостроение, карточные бои, рогалик",
"genres": ["Strategy", "RPG"],
"tags": {
"Deckbuilding": 1.6,
"Card Game": 1.4,
"Roguelike": 1.0,
"Turn-Based Combat": 0.9,
"Strategy": 0.7,
},
},
"visual-novel": {
"description": "Визуальная новелла, история, выборы",
"genres": ["Adventure"],
"tags": {
"Visual Novel": 1.6,
"Story Rich": 1.2,
"Anime": 0.9,
"Choices Matter": 0.8,
"Romance": 0.6,
},
},
"walking-sim": {
"description": "Спокойное исследование и атмосферная история",
"genres": ["Adventure", "Indie"],
"tags": {
"Walking Simulator": 1.6,
"Atmospheric": 1.2,
"Story Rich": 1.0,
"Exploration": 0.9,
"Mystery": 0.5,
},
},
"tower-defense": {
"description": "Защита базы, волны врагов, тактика",
"genres": ["Strategy"],
"tags": {
"Tower Defense": 1.6,
"Strategy": 1.0,
"Base Building": 0.8,
"Tactical": 0.7,
"Singleplayer": 0.5,
},
},
}
def connect(path=None):
path = path or DEFAULT_DB
con = sqlite3.connect(path, timeout=10)
con.row_factory = sqlite3.Row
con.execute("PRAGMA foreign_keys = ON")
con.execute("PRAGMA busy_timeout = 8000")
return con
def _ensure_column(con, table, column, declaration):
columns = {row[1] for row in con.execute(f"PRAGMA table_info({table})")}
if column not in columns:
con.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}")
def _get_schema_version(con):
try:
row = con.execute("SELECT value FROM schema_meta WHERE key = 'schema_version'").fetchone()
except sqlite3.OperationalError:
return 0
if not row or row[0] is None:
return 0
try:
return int(row[0])
except (TypeError, ValueError):
return 0
def _migration_1(con):
"""Add game_details.source_appid, introduced before schema versioning."""
_ensure_column(con, "game_details", "source_appid", "INTEGER")
def _plain_text(*parts):
text = " ".join(str(part) for part in parts if part)
text = re.sub(r"<[^>]+>", " ", text)
return " ".join(html.unescape(text).split())
def _search_tags(con, appid):
row = con.execute(
"""SELECT GROUP_CONCAT(tn.name, ' ') AS names
FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id
WHERE gt.appid = ?""", (appid,)).fetchone()
return (row[0] if row and row[0] else "") if row else ""
def refresh_search_index(con):
"""Rebuild the FTS5 index for every game."""
rows = con.execute("""
SELECT g.appid, g.name, d.short_description, d.about,
t.short_description AS short_ru, t.about AS about_ru
FROM games g
LEFT JOIN game_details d ON d.appid = g.appid
LEFT JOIN game_translations t ON t.appid = g.appid
WHERE LOWER(g.type) = 'game'
""").fetchall()
tags = {r[0]: r[1] for r in con.execute("""
SELECT gt.appid, GROUP_CONCAT(tn.name, ' ')
FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id
GROUP BY gt.appid
""")}
con.execute("DELETE FROM game_fts")
con.executemany(
"INSERT INTO game_fts(rowid, appid, name, description, tags) VALUES (?, ?, ?, ?, ?)",
[(r["appid"], r["appid"], r["name"],
_plain_text(r["short_description"], r["about"], r["short_ru"], r["about_ru"]),
tags.get(r["appid"], "")) for r in rows],
)
con.commit()
def refresh_search_game(con, appid):
"""Update one FTS5 row after details or tags change."""
row = con.execute("""
SELECT g.appid, g.name, d.short_description, d.about,
t.short_description AS short_ru, t.about AS about_ru
FROM games g
LEFT JOIN game_details d ON d.appid = g.appid
LEFT JOIN game_translations t ON t.appid = g.appid
WHERE g.appid = ? AND LOWER(g.type) = 'game'
""", (appid,)).fetchone()
con.execute("DELETE FROM game_fts WHERE rowid = ?", (appid,))
if row:
con.execute(
"INSERT INTO game_fts(rowid, appid, name, description, tags) VALUES (?, ?, ?, ?, ?)",
(appid, appid, row["name"],
_plain_text(row["short_description"], row["about"],
row["short_ru"], row["about_ru"]),
_search_tags(con, appid)),
)
con.commit()
def _migration_2(con):
"""Add the FTS5 search index over names, descriptions and tags."""
con.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS game_fts USING fts5(
appid UNINDEXED,
name,
description,
tags,
tokenize = 'unicode61 remove_diacritics 2'
)
""")
refresh_search_index(con)
GENRE_HOURS = {
"Massively Multiplayer": 80,
"RPG": 30,
"Strategy": 25,
"Simulation": 25,
"Adventure": 12,
"Action": 12,
"Racing": 10,
"Sports": 10,
"Free To Play": 10,
"Indie": 8,
"Casual": 6,
}
TAG_HOURS = {
"MMORPG": 80,
"JRPG": 40,
"Open World": 35,
"Colony Sim": 30,
"City Builder": 28,
"Management": 25,
"Farming Sim": 25,
"Survival": 25,
"Roguelike": 20,
"Sandbox": 20,
"Dungeon Crawler": 15,
"Roguelite": 15,
"Visual Novel": 12,
"Point & Click": 8,
"Puzzle": 8,
"Relaxing": 8,
"Walking Simulator": 6,
"Casual": 6,
"Short": 5,
}
def estimate_hours(genres, tag_names):
"""Rough playtime estimate from genres and Steam tags (no HLTB)."""
hours = max([GENRE_HOURS.get(genre, 0) for genre in genres] or [12])
hours = max([hours, *[TAG_HOURS.get(tag, 0) for tag in tag_names]])
if "Short" in tag_names:
hours = min(hours, TAG_HOURS["Short"])
return round(max(2.0, min(100.0, hours)), 1)
MONTHS = {
"янв": 1, "фев": 2, "мар": 3, "апр": 4, "май": 5, "мая": 5, "июн": 6,
"июл": 7, "авг": 8, "сен": 9, "сент": 9, "окт": 10, "ноя": 11, "дек": 12,
"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6,
"jul": 7, "aug": 8, "sep": 9, "sept": 9, "oct": 10, "nov": 11, "dec": 12,
}
def parse_release_date(value):
"""Parse common Steam store dates into YYYY-MM-DD or YYYY."""
text = " ".join(str(value or "").lower().replace("\xa0", " ").split())
if not text:
return None
year = re.search(r"\b(19|20)\d{2}\b", text)
if not year:
return None
year_value = int(year.group(0))
day_month = re.search(r"\b(\d{1,2})\s+([a-zа-яё]+)\.?", text)
if day_month:
month = MONTHS.get(day_month.group(2)[:4])
if month:
day = int(day_month.group(1))
if 1 <= day <= 31:
return f"{year_value:04d}-{month:02d}-{day:02d}"
month_day = re.search(r"\b([a-zа-яё]+)\.?\s+(\d{1,2}),?", text)
if month_day:
month = MONTHS.get(month_day.group(1)[:4])
if month:
day = int(month_day.group(2))
if 1 <= day <= 31:
return f"{year_value:04d}-{month:02d}-{day:02d}"
return f"{year_value:04d}"
def update_game_release(con, appid, value):
parsed = parse_release_date(value)
if not parsed:
return False
con.execute(
"""UPDATE games SET release_date = ?
WHERE appid = ? AND COALESCE(release_date, '') = ''""", (parsed, appid))
return True
def backfill_release_dates(con):
"""Fill missing games.release_date from localized Store dates."""
rows = con.execute("""
SELECT g.appid, d.release_date
FROM games g JOIN game_details d ON d.appid = g.appid
WHERE LOWER(g.type) = 'game'
AND COALESCE(g.release_date, '') = ''
AND COALESCE(d.release_date, '') <> ''
""").fetchall()
updates = []
for row in rows:
parsed = parse_release_date(row["release_date"])
if parsed:
updates.append((parsed, row["appid"]))
if updates:
con.executemany("UPDATE games SET release_date = ? WHERE appid = ?", updates)
con.commit()
return len(updates)
def refresh_duration_estimates(con):
"""Recompute games.estimated_hours for all games."""
genres = {}
for r in con.execute("SELECT appid, genre FROM game_genres"):
genres.setdefault(r["appid"], set()).add(r["genre"])
tags = {}
for r in con.execute("""SELECT gt.appid, tn.name
FROM game_tags gt JOIN tag_names tn ON tn.tag_id = gt.tag_id"""):
tags.setdefault(r["appid"], set()).add(r["name"])
updates = [
(estimate_hours(genres.get(r["appid"], set()), tags.get(r["appid"], set())), r["appid"])
for r in con.execute("SELECT appid FROM games WHERE LOWER(type) = 'game'")
]
con.executemany("UPDATE games SET estimated_hours = ? WHERE appid = ?", updates)
con.commit()
def _migration_3(con):
"""Add per-mood recommendation feedback."""
con.execute("""
CREATE TABLE IF NOT EXISTS reco_feedback (
appid INTEGER NOT NULL REFERENCES games(appid) ON DELETE CASCADE,
mood_key TEXT NOT NULL,
verdict TEXT NOT NULL CHECK (verdict IN ('like','dislike','played','ignore')),
created_at TEXT NOT NULL,
PRIMARY KEY (appid, mood_key)
)
""")
con.execute("CREATE INDEX IF NOT EXISTS idx_reco_feedback_mood "
"ON reco_feedback(mood_key, verdict)")
def _migration_4(con):
"""Add estimated_hours and populate it for existing games."""
_ensure_column(con, "games", "estimated_hours", "REAL")
refresh_duration_estimates(con)
def _migration_5(con):
"""Backfill release years from localized Store dates."""
backfill_release_dates(con)
MIGRATIONS = {
1: _migration_1,
2: _migration_2,
3: _migration_3,
4: _migration_4,
5: _migration_5,
}
def init(con):
"""Create or upgrade the database schema.
Migrations run in order from the stored ``schema_meta.schema_version``.
A database created by a newer release is rejected instead of being
silently modified by an older one.
"""
version = _get_schema_version(con)
if version > SCHEMA_VERSION:
raise RuntimeError(
f"database schema version {version} is newer than supported {SCHEMA_VERSION}")
with open(SCHEMA_PATH, encoding="utf-8") as f:
con.executescript(f.read())
for target in range(version + 1, SCHEMA_VERSION + 1):
MIGRATIONS[target](con)
con.execute("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('schema_version', ?)",
(str(SCHEMA_VERSION),))
con.commit()
def seed_moods(con):
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
for name, preset in MOOD_PRESETS.items():
con.execute(
"""INSERT INTO moods (name, description, genres, tags, updated_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
description = excluded.description,
genres = excluded.genres,
tags = excluded.tags,
updated_at = excluded.updated_at""",
(name, preset["description"], json.dumps(preset["genres"]),
json.dumps(preset["tags"]), now),
)
con.commit()