uzchess_hackathon_2 / chess_api.py
MrSimple07's picture
new structure for the overall part
80e55f8
import requests
import time
import logging
import pandas as pd
from core import analyze_opponent_openings
from ai_integration import get_counter_debuts
from collections import Counter
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def get_user_games_from_chess_com(username):
try:
logger.info(f"Fetching games for: {username}")
username = username.strip().lower()
user_url = f"https://api.chess.com/pub/player/{username}"
response = requests.get(user_url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'})
if response.status_code != 200:
return None, f"❌ Foydalanuvchi topilmadi: {username}"
archives_url = f"https://api.chess.com/pub/player/{username}/games/archives"
response = requests.get(archives_url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'})
if response.status_code != 200:
return None, "❌ O'yinlar arxivi topilmadi."
archives = response.json()['archives']
if not archives:
return None, "❌ O'yinlar topilmadi."
all_games = []
for archive_url in reversed(archives[-3:]):
time.sleep(0.3)
response = requests.get(archive_url, timeout=10, headers={'User-Agent': 'Mozilla/5.0'})
if response.status_code == 200:
games = response.json()['games']
all_games.extend(games)
if len(all_games) >= 50:
break
rapid_games = [g for g in all_games if g.get('time_class') in ['rapid', 'blitz']]
if not rapid_games:
rapid_games = all_games[:50]
pgn_list = [g['pgn'] for g in rapid_games[:50] if 'pgn' in g]
if not pgn_list:
return None, "❌ PGN formatdagi o'yinlar topilmadi."
return pgn_list, None
except Exception as e:
logger.error(f"Error fetching games: {str(e)}")
return None, f"❌ Xatolik: {str(e)}"
def analyze_chess_com_user(username, user_repertoire, user_color="Oq"):
if not username or not username.strip():
return "❌ Iltimos, Chess.com foydalanuvchi nomini kiriting!"
status_msg = f"πŸ” {username} foydalanuvchisi o'yinlari yuklanmoqda...\n\n"
pgn_list, error = get_user_games_from_chess_com(username)
if error:
return error
status_msg += f"βœ… {len(pgn_list)} ta o'yin topildi!\n\n"
status_msg += "πŸ“Š Debyutlar tahlil qilinmoqda...\n\n"
opponent_openings = analyze_opponent_openings(pgn_list, username)
if not opponent_openings:
return status_msg + "❌ Raqib debyutlari aniqlanmadi."
white_openings = [o for o in opponent_openings if o['opponent_color'] == 'oq']
black_openings = [o for o in opponent_openings if o['opponent_color'] == 'qora']
white_counter = Counter([o['name'] for o in white_openings])
black_counter = Counter([o['name'] for o in black_openings])
analysis_text = "# πŸ“ˆ RAQIB DEBYUTLARI TAHLILI\n\n"
analysis_text += f"**Foydalanuvchi:** {username}\n"
analysis_text += f"**Tahlil qilingan o'yinlar:** {len(pgn_list)}\n\n"
if white_openings:
analysis_text += "## 🎯 Raqib OQ rang bilan o'ynaganida:\n\n"
for opening, count in white_counter.most_common(5):
analysis_text += f"- **{opening}** ({count} marta)\n"
analysis_text += "\n"
if black_openings:
analysis_text += "## 🎯 Raqib QORA rang bilan o'ynaganida:\n\n"
for opening, count in black_counter.most_common(5):
analysis_text += f"- **{opening}** ({count} marta)\n"
analysis_text += "\n"
debuts_for_ai = ""
if white_counter:
debuts_for_ai += "Raqib OQ bilan: " + ", ".join([o for o, _ in white_counter.most_common(3)]) + "\n"
if black_counter:
debuts_for_ai += "Raqib QORA bilan: " + ", ".join([o for o, _ in black_counter.most_common(3)])
analysis_text += "\n---\n\n"
analysis_text += "## πŸ€– AI TAVSIYALARI\n\n"
try:
ai_response = get_counter_debuts(debuts_for_ai, user_color, user_repertoire)
analysis_text += ai_response
except Exception as e:
analysis_text += f"❌ AI tahlil xatosi: {str(e)}"
return analysis_text