#!/usr/bin/env python3
from __future__ import annotations
import html
import json
import os
import re
import threading
import time
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.error import URLError
from urllib.parse import parse_qs, urlparse
from urllib.request import Request, urlopen
from dotenv import load_dotenv
from analyze import get_json, parse_form
from notify_interesting_matches import ENV_FILE, InterestingMatch, collect_interesting_matches, top_teams_for_league
from send_demo_model_style import generate_card
from send_safe_matches_image import CARDS_DIR, send_photo, to_card_match
HOST = "127.0.0.1"
PORT = 8012
CARD_PATH = CARDS_DIR / "web_safe_matches_card.png"
ICON_PATH = CARDS_DIR / "gabfoot_icon.png"
SITE_ASSETS_DIR = Path(__file__).resolve().parent / "site_assets"
DASHBOARD_HERO_IMAGE_PATH = SITE_ASSETS_DIR / "dashboard-hero.jpg"
BOTOLA_LEAGUE_ID = 530
TEAM_CACHE: dict[int, dict] = {}
APP_CACHE_DIR = Path(__file__).resolve().parent / ".cache"
DASHBOARD_CACHE_FILE = APP_CACHE_DIR / "dashboard_cache.json"
PREFERRED_PUBLIC_URL_FILE = APP_CACHE_DIR / "preferred_public_url.txt"
DASHBOARD_CACHE_TTL_SECONDS = 15 * 60
DASHBOARD_CACHE_STALE_SECONDS = 6 * 3600
_DASHBOARD_CACHE: dict[str, dict[str, object]] = {}
_CACHE_LOCK = threading.Lock()
_REFRESH_IN_FLIGHT: set[str] = set()
ARTICLE_IMAGE_CACHE: dict[str, str] = {}
ARTICLE_IMAGE_LOCK = threading.Lock()
ARTICLE_IMAGE_FETCH_ENABLED = os.getenv("GABFOOT_FETCH_ARTICLE_IMAGES", "").strip() == "1"
UPDATES_FILE = Path(__file__).resolve().parent / "updates.json"
def configured_public_url() -> str:
candidates = [
os.getenv("GABFOOT_PUBLIC_URL", "").strip(),
os.getenv("GABFOOT_SITE_URL", "").strip(),
]
if PREFERRED_PUBLIC_URL_FILE.exists():
try:
candidates.append(PREFERRED_PUBLIC_URL_FILE.read_text().strip())
except OSError:
pass
for candidate in candidates:
if candidate.startswith("http://") or candidate.startswith("https://"):
return candidate.rstrip("/")
return ""
def load_site_updates() -> list[dict[str, object]]:
try:
payload = json.loads(UPDATES_FILE.read_text(encoding="utf-8"))
except OSError:
return []
except json.JSONDecodeError:
return []
if not isinstance(payload, list):
return []
cleaned: list[dict[str, object]] = []
for entry in payload:
if not isinstance(entry, dict):
continue
bullets = entry.get("bullets", [])
if not isinstance(bullets, list):
bullets = []
cleaned.append(
{
"date": str(entry.get("date", "")).strip(),
"label": str(entry.get("label", "Produit")).strip() or "Produit",
"title": str(entry.get("title", "")).strip(),
"summary": str(entry.get("summary", "")).strip(),
"bullets": [str(bullet).strip() for bullet in bullets if str(bullet).strip()],
}
)
return cleaned
def request_scheme(handler: BaseHTTPRequestHandler) -> str:
forwarded = handler.headers.get("X-Forwarded-Proto", "").split(",")[0].strip().lower()
if forwarded in {"http", "https"}:
return forwarded
if os.getenv("PORT"):
return "https"
return "http"
def request_host(handler: BaseHTTPRequestHandler) -> str:
forwarded = handler.headers.get("X-Forwarded-Host", "").split(",")[0].strip()
if forwarded:
return forwarded
host = handler.headers.get("Host", "").split(",")[0].strip()
if host:
return host
return f"{HOST}:{PORT}"
def request_base_url(handler: BaseHTTPRequestHandler) -> str:
configured = configured_public_url()
if configured:
return configured
return f"{request_scheme(handler)}://{request_host(handler)}"
def absolute_url(base_url: str, path: str) -> str:
normalized = path if path.startswith("/") else f"/{path}"
return f"{base_url.rstrip('/')}{normalized}"
def dashboard_cache_key(limit: int, min_percent: int) -> str:
return f"{limit}:{min_percent}"
def serialize_match(match: InterestingMatch) -> dict[str, object]:
return {
"match_id": match.match_id,
"league_id": match.league_id,
"league_name": match.league_name,
"tournament_name": match.tournament_name,
"kickoff_utc": match.kickoff_utc,
"page_url": match.page_url,
"home_name": match.home_name,
"away_name": match.away_name,
"home_id": match.home_id,
"away_id": match.away_id,
"home_form": match.home_form,
"away_form": match.away_form,
"home_points": match.home_points,
"away_points": match.away_points,
"home_history_score": match.home_history_score,
"away_history_score": match.away_history_score,
"h2h_edge": match.h2h_edge,
"injuries_edge": match.injuries_edge,
"home_rank": match.home_rank,
"away_rank": match.away_rank,
"home_goals_per_match": match.home_goals_per_match,
"away_goals_per_match": match.away_goals_per_match,
"home_conceded_per_match": match.home_conceded_per_match,
"away_conceded_per_match": match.away_conceded_per_match,
"home_key_player": match.home_key_player,
"away_key_player": match.away_key_player,
"prediction": match.prediction,
"confidence": match.confidence,
"sureness_percent": match.sureness_percent,
"consensus_notes": match.consensus_notes,
"interest_score": match.interest_score,
"why": match.why,
}
def deserialize_match(payload: dict[str, object]) -> InterestingMatch:
return InterestingMatch(**payload)
def load_dashboard_cache() -> None:
if not DASHBOARD_CACHE_FILE.exists():
return
try:
payload = json.loads(DASHBOARD_CACHE_FILE.read_text())
except Exception:
return
if not isinstance(payload, dict):
return
for key, entry in payload.items():
if isinstance(entry, dict):
_DASHBOARD_CACHE[key] = entry
def persist_dashboard_cache() -> None:
APP_CACHE_DIR.mkdir(parents=True, exist_ok=True)
DASHBOARD_CACHE_FILE.write_text(json.dumps(_DASHBOARD_CACHE, ensure_ascii=True, indent=2))
def compute_dashboard_payload(limit: int, min_percent: int) -> dict[str, object]:
matches, card_path = build_card(limit=limit, min_percent=min_percent)
botola = safe_botola_predictions()
tennis = safe_tennis_world_matches()
articles = safe_football_articles(matches, botola)
return {
"updated_at": time.time(),
"limit": limit,
"min_percent": min_percent,
"has_card": bool(card_path and card_path.exists()),
"matches": [serialize_match(match) for match in matches],
"botola": botola,
"tennis": tennis,
"articles": articles,
}
def refresh_dashboard_cache(limit: int, min_percent: int) -> None:
key = dashboard_cache_key(limit, min_percent)
try:
payload = compute_dashboard_payload(limit=limit, min_percent=min_percent)
with _CACHE_LOCK:
_DASHBOARD_CACHE[key] = payload
persist_dashboard_cache()
finally:
with _CACHE_LOCK:
_REFRESH_IN_FLIGHT.discard(key)
def ensure_dashboard_refresh(limit: int, min_percent: int) -> None:
key = dashboard_cache_key(limit, min_percent)
with _CACHE_LOCK:
if key in _REFRESH_IN_FLIGHT:
return
_REFRESH_IN_FLIGHT.add(key)
thread = threading.Thread(target=refresh_dashboard_cache, args=(limit, min_percent), daemon=True)
thread.start()
def get_cached_dashboard_payload(limit: int, min_percent: int) -> tuple[dict[str, object] | None, bool]:
key = dashboard_cache_key(limit, min_percent)
now = time.time()
with _CACHE_LOCK:
entry = _DASHBOARD_CACHE.get(key)
if entry:
age = now - float(entry.get("updated_at", 0))
if age <= DASHBOARD_CACHE_TTL_SECONDS:
return entry, False
if age <= DASHBOARD_CACHE_STALE_SECONDS:
ensure_dashboard_refresh(limit=limit, min_percent=min_percent)
return entry, True
ensure_dashboard_refresh(limit=limit, min_percent=min_percent)
return None, True
def get_fresh_dashboard_payload(limit: int, min_percent: int) -> dict[str, object]:
payload = compute_dashboard_payload(limit=limit, min_percent=min_percent)
key = dashboard_cache_key(limit, min_percent)
with _CACHE_LOCK:
_DASHBOARD_CACHE[key] = payload
persist_dashboard_cache()
return payload
def get_team_payload(team_id: int) -> dict:
if team_id not in TEAM_CACHE:
TEAM_CACHE[team_id] = get_json(f"https://www.fotmob.com/api/teams?id={team_id}", timeout=35)
return TEAM_CACHE[team_id]
def find_meta_image(page_html: str) -> str:
patterns = (
r']+property=["\']og:image["\'][^>]+content=["\']([^"\']+)',
r']+content=["\']([^"\']+)["\'][^>]+property=["\']og:image["\']',
r']+name=["\']twitter:image["\'][^>]+content=["\']([^"\']+)',
r']+content=["\']([^"\']+)["\'][^>]+name=["\']twitter:image["\']',
)
for pattern in patterns:
match = re.search(pattern, page_html, re.IGNORECASE)
if match:
return html.unescape(match.group(1)).strip()
return ""
def resolve_article_image(article_url: str, fallback: str = "") -> str:
article_url = article_url.strip()
if not article_url:
return fallback
with ARTICLE_IMAGE_LOCK:
if article_url in ARTICLE_IMAGE_CACHE:
cached = ARTICLE_IMAGE_CACHE[article_url]
return cached or fallback
# Avoid blocking public routes on third-party article pages unless explicitly enabled.
if not ARTICLE_IMAGE_FETCH_ENABLED:
return fallback
image_url = ""
try:
request = Request(
article_url,
headers={
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
)
},
)
with urlopen(request, timeout=3) as response:
payload = response.read(300_000).decode("utf-8", "ignore")
image_url = find_meta_image(payload)
except (TimeoutError, URLError, ValueError, OSError):
image_url = ""
with ARTICLE_IMAGE_LOCK:
ARTICLE_IMAGE_CACHE[article_url] = image_url
return image_url or fallback
def form_points(record: str) -> int:
score = 0
for part in record.split():
if part.endswith("G"):
score += int(part[:-1]) * 3
elif part.endswith("N"):
score += int(part[:-1])
return score
def botola_predictions(limit: int = 6) -> list[dict[str, object]]:
payload = get_json(f"https://www.fotmob.com/api/leagues?id={BOTOLA_LEAGUE_ID}", timeout=40)
table_rows = (payload.get("table") or [{}])[0].get("data", {}).get("table", {}).get("all", [])
standings = {int(row["id"]): row for row in table_rows if row.get("id")}
all_matches = payload.get("fixtures", {}).get("allMatches", [])
pending = [match for match in all_matches if not match.get("status", {}).get("finished")]
pending.sort(key=lambda item: item.get("status", {}).get("utcTime", ""))
out: list[dict[str, object]] = []
for match in pending[:limit]:
home = match.get("home", {})
away = match.get("away", {})
home_id = int(home.get("id", 0))
away_id = int(away.get("id", 0))
if not home_id or not away_id:
continue
home_payload = get_team_payload(home_id)
away_payload = get_team_payload(away_id)
home_record = parse_form(home_payload)["record"]
away_record = parse_form(away_payload)["record"]
home_row = standings.get(home_id, {})
away_row = standings.get(away_id, {})
home_score = (
form_points(home_record)
+ int(home_row.get("pts", 0))
+ int(home_row.get("goalConDiff", 0))
+ 2
)
away_score = (
form_points(away_record)
+ int(away_row.get("pts", 0))
+ int(away_row.get("goalConDiff", 0))
)
delta = home_score - away_score
if delta >= 6:
prediction = "1"
elif delta <= -6:
prediction = "2"
else:
prediction = "X"
confidence = max(54, min(84, 56 + abs(delta) * 2))
why = []
if home_row.get("idx") and away_row.get("idx"):
why.append(f"Classement {home_row.get('idx')}e vs {away_row.get('idx')}e")
if form_points(home_record) != form_points(away_record):
side = home.get("shortName") if form_points(home_record) > form_points(away_record) else away.get("shortName")
why.append(f"Forme recente pour {side}")
if int(home_row.get("goalConDiff", 0)) != int(away_row.get("goalConDiff", 0)):
side = home.get("shortName") if int(home_row.get("goalConDiff", 0)) > int(away_row.get("goalConDiff", 0)) else away.get("shortName")
why.append(f"Difference de buts favorable a {side}")
out.append(
{
"kickoff": fmt_kickoff(match.get("status", {}).get("utcTime", "")),
"home": home.get("name", ""),
"away": away.get("name", ""),
"homeId": home_id,
"awayId": away_id,
"prediction": prediction,
"confidence": confidence,
"homeRecord": home_record,
"awayRecord": away_record,
"homeRank": home_row.get("idx"),
"awayRank": away_row.get("idx"),
"why": why[:3],
"status": match.get("status", {}).get("reason", {}).get("short", ""),
}
)
return out
def tennis_world_matches(limit: int = 8) -> list[dict[str, object]]:
out: list[dict[str, object]] = []
for circuit in ("atp", "wta"):
payload = get_json(f"https://site.api.espn.com/apis/site/v2/sports/tennis/{circuit}/scoreboard", timeout=40)
for event in payload.get("events", [])[:2]:
tournament = event.get("name") or event.get("shortName") or circuit.upper()
for grouping in event.get("groupings", []):
for competition in grouping.get("competitions", [])[:4]:
status = competition.get("status", {}).get("type", {})
competitors = competition.get("competitors", [])
if len(competitors) < 2:
continue
players = sorted(competitors, key=lambda item: item.get("order", 99))
p1 = players[0].get("athlete", {}).get("displayName", "Joueur 1")
p2 = players[1].get("athlete", {}).get("displayName", "Joueur 2")
lines1 = "-".join(str(int(s.get("value", 0))) for s in players[0].get("linescores", []) if s.get("value") is not None) or "-"
lines2 = "-".join(str(int(s.get("value", 0))) for s in players[1].get("linescores", []) if s.get("value") is not None) or "-"
venue = competition.get("venue", {})
out.append(
{
"tour": circuit.upper(),
"tournament": tournament,
"group": grouping.get("grouping", {}).get("displayName", ""),
"player1": p1,
"player2": p2,
"score": f"{lines1} / {lines2}",
"status": status.get("shortDetail") or status.get("description") or "",
"state": status.get("state", ""),
"venue": venue.get("fullName", ""),
"court": venue.get("court", ""),
}
)
if len(out) >= limit:
return out
return out[:limit]
def safe_botola_predictions(limit: int = 6) -> list[dict[str, object]]:
try:
return botola_predictions(limit=limit)
except Exception:
return []
def safe_tennis_world_matches(limit: int = 8) -> list[dict[str, object]]:
try:
return tennis_world_matches(limit=limit)
except Exception:
return []
def football_articles(matches: list[InterestingMatch], botola: list[dict[str, object]], limit: int = 12) -> list[dict[str, str]]:
seen_team_ids: list[int] = []
for match in matches[:4]:
for team_id in (match.home_id, match.away_id):
if team_id not in seen_team_ids:
seen_team_ids.append(team_id)
for match in botola[:4]:
for team_id in (int(match.get("homeId", 0)), int(match.get("awayId", 0))):
if team_id and team_id not in seen_team_ids:
seen_team_ids.append(team_id)
seen_articles: set[str] = set()
articles: list[dict[str, str]] = []
for team_id in seen_team_ids:
payload = get_team_payload(team_id)
team_name = payload.get("details", {}).get("name", "")
team_logo = (
payload.get("details", {}).get("sportsTeamJSONLD", {}).get("logo")
or payload.get("details", {}).get("logo")
or ""
)
items = (payload.get("overview", {}).get("newsSummary") or {}).get("items", [])
for item in items[:4]:
source = item.get("source", {}) or {}
url = str(source.get("uri", "")).strip()
title = str(source.get("title", "")).strip()
summary = str(item.get("summary", "")).strip()
source_name = str(source.get("sourceName", "Source")).strip()
key = url or title
if not key or key in seen_articles:
continue
seen_articles.add(key)
article_image = resolve_article_image(url, fallback=str(team_logo).strip())
articles.append(
{
"team": team_name,
"title": title or "Article football",
"summary": summary or "Resume indisponible.",
"url": url,
"source": source_name,
"image": article_image,
"logo": str(team_logo).strip(),
}
)
if len(articles) >= limit:
return articles
return articles
def safe_football_articles(matches: list[InterestingMatch], botola: list[dict[str, object]], limit: int = 12) -> list[dict[str, str]]:
try:
return football_articles(matches, botola, limit=limit)
except Exception:
return []
def interaction_script() -> str:
return """
"""
def render_pick_badge(prediction: str, percent: int) -> str:
return f"""
{html.escape(prediction)}{percent}%
"""
def render_favorite_button(
match_id: int,
title: str,
kickoff: str,
prediction: str,
percent: int,
detail_url: str,
) -> str:
return f"""
"""
def pick_theme(prediction: str) -> str:
normalized = prediction.strip().upper()
if "1" in normalized and "2" not in normalized and "X" not in normalized:
return "pick-home"
if "2" in normalized and "1" not in normalized and "X" not in normalized:
return "pick-away"
if "X" in normalized and "1" not in normalized and "2" not in normalized:
return "pick-draw"
return "pick-mixed"
def confidence_theme(percent: int) -> str:
if percent >= 85:
return "confidence-elite"
if percent >= 75:
return "confidence-strong"
return "confidence-medium"
def render_confidence_meter(percent: int) -> str:
width = max(10, min(100, percent))
return f"""
"""
)
if slot not in grouped_rows:
grouped_rows[slot] = []
ordered_slots.append(slot)
grouped_rows[slot].append(row)
if not ordered_slots:
return ''
bodies = []
for slot in ordered_slots:
bodies.append(
f"""
Heure des matchs : {html.escape(slot)}
{''.join(grouped_rows[slot])}
"""
)
return f"""
Heure
Match
Pick
Forme
Stats
Joueurs / Consensus
Details match
{''.join(bodies)}
"""
def render_mobile_pick_cards(matches: list[InterestingMatch]) -> str:
if not matches:
return ''
cards: list[str] = []
for match in matches:
cards.append(
f"""
Rang {match['homeRank'] or '-'} / {match['awayRank'] or '-'}
Etat {html.escape(str(match['status'])) or 'A venir'}
"""
)
if slot not in grouped_rows:
grouped_rows[slot] = []
ordered_slots.append(slot)
grouped_rows[slot].append(row)
if not ordered_slots:
return ''
bodies = []
for slot in ordered_slots:
bodies.append(
f"""
Heure des matchs : {html.escape(slot)}
{''.join(grouped_rows[slot])}
"""
)
return f"""
Horaire
Match
Pronostic
Lecture rapide
{''.join(bodies)}
"""
def render_tennis_table(tennis: list[dict[str, object]]) -> str:
grouped_rows: dict[str, list[str]] = {}
ordered_slots: list[str] = []
for item in tennis:
status = str(item.get("status", "")).strip()
slot = status[:16] if status else str(item.get("tournament", "ATP/WTA"))
row = (
f"""
{html.escape(str(item['tour']))}
{html.escape(str(item['group']))}
{html.escape(str(item['tournament']))}
{html.escape(str(item['player1']))} vs {html.escape(str(item['player2']))}
{html.escape(str(item['score'])[:1] if str(item['score']) else '-')}
{html.escape(status or 'En cours')}
{render_confidence_meter(68)}
Score {html.escape(str(item['score']))}
Lieu {html.escape(str(item['venue']))}{' | ' + html.escape(str(item['court'])) if item['court'] else ''}
"""
)
if slot not in grouped_rows:
grouped_rows[slot] = []
ordered_slots.append(slot)
grouped_rows[slot].append(row)
if not ordered_slots:
return ''
bodies = []
for slot in ordered_slots:
bodies.append(
f"""
Heure / statut : {html.escape(slot)}
{''.join(grouped_rows[slot])}
"""
)
return f"""
Circuit
Match
Score / Etat
Details
{''.join(bodies)}
"""
def render_articles_grid(articles: list[dict[str, str]]) -> str:
cards = []
for item in articles:
image = str(item.get("image", "")).strip()
visual = (
f''
if image
else '
GABFOOT
'
)
logo = str(item.get("logo", "")).strip()
badge = (
f''
if logo
else '
GF
'
)
link = (
f'Lire l'article'
if item.get("url")
else ""
)
cards.append(
f"""
Des pronostics foot plus propres, plus premium et plus lisibles.
GABFOOT prend l'esprit d'un gros site de pronostics et le rend plus editorial, plus clair et plus credible. Les matchs forts, la Botola, les news clubs et le poster Telegram vivent dans une meme direction visuelle, avec une palette pensee pour inspirer confiance.
Board principalLes picks les plus solides remontent avant le reste.
Radar editorialLe flux news complete le signal au lieu de le parasiter.
Sortie TelegramLe site produit aussi une image prete a publier.
{len(matches)}signals majeurs actifs avec ton filtre a {min_percent}%.
{avg_confidence}%fiabilite moyenne lue en une seconde.
{len(botola) + len(tennis)}boards additionnels entre Maroc et tennis.
{len(articles)}angles editoriaux pour habiller le produit.
{len(site_updates)}mises a jour produit deja publiees.
{market_strip}
{notice_html}
{featured_match_html}
{poster_visual}
Telegram studio
Une affiche prete a diffuser sans sortir de l'univers GABFOOT.
Le site ne se limite pas a l'inspiration visuelle. Il pousse aussi une image exploitable pour les canaux Telegram, avec la meme logique de selection que le dashboard.
Une signature plus forte que le simple tableau de pronostics.
Le projet garde la richesse d'un site de pronostics populaire, mais remonte en gamme avec une meilleure hierarchie, une couleur plus maitrisee et une lecture plus rapide des signaux utiles.
01
Un ton plus credible
Fond sable chaud, vert profond et accent or. Le rendu evoque l'analyse et la confiance, pas le casino agressif ni la page surchargee.
02
Une lecture plus rapide
Les picks importants remontent tout de suite. En quelques secondes, tu vois les matchs forts, le niveau de fiabilite et les boards annexes qui comptent.
03
Un produit plus complet
Dashboard, fiches match, favoris personnels, flux editorial et poster Telegram travaillent ensemble au lieu de donner l'impression de blocs isoles.
Lecture instantanee
Le niveau du flux actuel, sans ouvrir dix pages.
La home montre deja le ton du produit. Les meilleures cartes doivent suffire a convaincre que GABFOOT sait trier, cadrer et raconter les matchs qui meritent l'attention.
Une colonne centrale claire, des branches utiles, aucun bloc perdu.
La home doit expliquer tout le produit. Le dashboard porte l'execution, les boards annexes elargissent la couverture, l'editorial habille le site et le journal produit montre que la plateforme avance.
01
Accueil
La page d'entree pose le ton, presente le signal fort et oriente immediatement vers les axes qui comptent.
Chaque bloc a maintenant une fonction nette dans l'architecture globale. Les liens ne se battent plus entre eux et gardent la meme hierarchie visuelle.
Des picks mieux cadres, plus credibles et plus lisibles qu'un portail surcharge.
Le dashboard GABFOOT rassemble les matchs les plus solides, la Botola, le tennis, les news et le poster Telegram dans une seule salle de controle. Mise a jour: {now}