Spaces:
Sleeping
Sleeping
import datetime | |
import requests | |
import pytz | |
import yaml | |
import os | |
from typing import Dict, Union | |
from bs4 import BeautifulSoup | |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
from tools.final_answer import FinalAnswerTool | |
from Gradio_UI import GradioUI | |
# Load the API key from Hugging Face Spaces secrets (environment variable) | |
API_KEY = os.getenv("CRICKETDATA_API_KEY", "default_key_if_not_found") | |
HF_TOKEN = os.getenv("HF_TOKEN", "default_hf_token_if_not_found") | |
BASE_URL = "https://api.cricketdata.org/v1" | |
# Custom Tool: Analyze Cricketer Form | |
def analyze_cricketer_form(player_name: str, role: str) -> str: | |
"""Analyzes the recent form of a cricketer based on their role. | |
Args: | |
player_name: The name of the cricketer. | |
role: The role of the player (batter, bowler, wicketkeeper, fielder). | |
""" | |
try: | |
# Fetch player ID from API | |
player_id = get_player_id(player_name) | |
if not player_id: | |
return f"Player '{player_name}' not found." | |
# Fetch basic player details | |
player_details = get_player_details(player_id) | |
# Scrape detailed stats | |
detailed_stats = scrape_cricketer_stats(player_name, role) | |
# Generate form analysis | |
return format_analysis(player_name, role, player_details, detailed_stats) | |
except Exception as e: | |
return f"Error analyzing cricketer's form: {str(e)}" | |
def get_player_id(player_name: str): | |
response = requests.get(f"{BASE_URL}/players?name={player_name}", headers={"Authorization": f"Bearer {API_KEY}"}) | |
if response.status_code == 200: | |
data = response.json() | |
return data.get("id") | |
return None | |
def get_player_details(player_id: str): | |
response = requests.get(f"{BASE_URL}/player/{player_id}", headers={"Authorization": f"Bearer {API_KEY}"}) | |
if response.status_code == 200: | |
return response.json() | |
return {} | |
def scrape_cricketer_stats(player_name: str, role: str): | |
"""Scrapes recent performance stats from an online cricket stats website.""" | |
try: | |
search_url = f"https://stats.espncricinfo.com/ci/engine/player/{player_name.replace(' ', '_')}.html" | |
headers = {"User-Agent": "Mozilla/5.0"} | |
response = requests.get(search_url, headers=headers) | |
if response.status_code != 200: | |
return {"error": "Failed to fetch data from ESPN Cricinfo"} | |
soup = BeautifulSoup(response.text, "html.parser") | |
if role.lower() == "batter": | |
stats = { | |
"last_50_scores": extract_batting_scores(soup), | |
"batting_avg": extract_batting_average(soup), | |
"strike_rate": extract_strike_rate(soup), | |
} | |
elif role.lower() == "bowler": | |
stats = { | |
"last_50_wickets": extract_wickets(soup), | |
"bowling_economy": extract_bowling_economy(soup), | |
"bowling_speed": extract_bowling_speed(soup), | |
} | |
elif role.lower() == "wicketkeeper": | |
stats = { | |
"catches": extract_catches(soup), | |
"stumpings": extract_stumpings(soup), | |
"missed_stumpings": extract_missed_stumpings(soup), | |
} | |
elif role.lower() == "fielder": | |
stats = { | |
"catches": extract_fielder_catches(soup), | |
"direct_runouts": extract_direct_runouts(soup), | |
} | |
else: | |
stats = {"error": "Invalid role specified"} | |
return stats | |
except Exception as e: | |
return {"error": f"Error scraping data: {str(e)}"} | |
def format_analysis(player_name, role, player_details, detailed_stats): | |
return f""" | |
Cricketer: {player_name} | |
Role: {role} | |
Country: {player_details.get('country', 'Unknown')} | |
Batting Style: {player_details.get('battingStyle', 'Unknown')} | |
Bowling Style: {player_details.get('bowlingStyle', 'Unknown')} | |
Recent Performance: | |
{detailed_stats} | |
""" | |
# Initialize tools | |
final_answer = FinalAnswerTool() | |
# Model setup | |
model = HfApiModel( | |
max_tokens=2096, | |
temperature=0.5, | |
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud', | |
custom_role_conversions=None, | |
) | |
# Load prompt templates | |
with open("prompts.yaml", 'r') as stream: | |
prompt_templates = yaml.safe_load(stream) | |
# Initialize the agent | |
agent = CodeAgent( | |
model=model, | |
tools=[final_answer, analyze_cricketer_form], | |
max_steps=6, | |
verbosity_level=1, | |
grammar=None, | |
prompt_templates=prompt_templates | |
) | |
# Launch the Gradio UI | |
if __name__ == "__main__": | |
GradioUI(agent).launch() | |
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder: | |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' | |