21spl commited on
Commit
60a0324
·
verified ·
1 Parent(s): 1b5ab61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -95
app.py CHANGED
@@ -4,113 +4,49 @@ import pytz
4
  import yaml
5
  import os
6
  from typing import Dict, Union
7
- from bs4 import BeautifulSoup
8
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
9
  from tools.final_answer import FinalAnswerTool
10
  from Gradio_UI import GradioUI
11
 
12
- # Load the API key from Hugging Face Spaces secrets (environment variable)
13
- API_KEY = os.getenv("CRICKETDATA_API_KEY", "default_key_if_not_found")
 
 
14
  HF_TOKEN = os.getenv("HF_TOKEN", "default_hf_token_if_not_found")
15
- BASE_URL = "https://api.cricketdata.org/v1"
16
 
17
- # Custom Tool: Analyze Cricketer Form
18
  @tool
19
- def analyze_cricketer_form(player_name: str, role: str) -> str:
20
- """Analyzes the recent form of a cricketer based on their role.
21
  Args:
22
- player_name: The name of the cricketer.
23
- role: The role of the player (batter, bowler, wicketkeeper, fielder).
24
  """
25
  try:
26
- # Fetch player ID from API
27
- player_id = get_player_id(player_name)
28
- if not player_id:
29
- return f"Player '{player_name}' not found."
30
-
31
- # Fetch basic player details
32
- player_details = get_player_details(player_id)
33
 
34
- # Scrape detailed stats
35
- detailed_stats = scrape_cricketer_stats(player_name, role)
36
-
37
- # Generate form analysis
38
- return format_analysis(player_name, role, player_details, detailed_stats)
39
-
40
- except Exception as e:
41
- return f"Error analyzing cricketer's form: {str(e)}"
42
-
43
-
44
- def get_player_id(player_name: str):
45
- response = requests.get(f"{BASE_URL}/players?name={player_name}", headers={"Authorization": f"Bearer {API_KEY}"})
46
- if response.status_code == 200:
47
- data = response.json()
48
- return data.get("id")
49
- return None
50
-
51
-
52
- def get_player_details(player_id: str):
53
- response = requests.get(f"{BASE_URL}/player/{player_id}", headers={"Authorization": f"Bearer {API_KEY}"})
54
- if response.status_code == 200:
55
- return response.json()
56
- return {}
57
 
 
 
 
58
 
59
- def scrape_cricketer_stats(player_name: str, role: str):
60
- """Scrapes recent performance stats from an online cricket stats website."""
61
- try:
62
- search_url = f"https://stats.espncricinfo.com/ci/engine/player/{player_name.replace(' ', '_')}.html"
63
- headers = {"User-Agent": "Mozilla/5.0"}
64
- response = requests.get(search_url, headers=headers)
65
-
66
- if response.status_code != 200:
67
- return {"error": "Failed to fetch data from ESPN Cricinfo"}
68
-
69
- soup = BeautifulSoup(response.text, "html.parser")
70
-
71
- if role.lower() == "batter":
72
- stats = {
73
- "last_50_scores": extract_batting_scores(soup),
74
- "batting_avg": extract_batting_average(soup),
75
- "strike_rate": extract_strike_rate(soup),
76
- }
77
- elif role.lower() == "bowler":
78
- stats = {
79
- "last_50_wickets": extract_wickets(soup),
80
- "bowling_economy": extract_bowling_economy(soup),
81
- "bowling_speed": extract_bowling_speed(soup),
82
- }
83
- elif role.lower() == "wicketkeeper":
84
- stats = {
85
- "catches": extract_catches(soup),
86
- "stumpings": extract_stumpings(soup),
87
- "missed_stumpings": extract_missed_stumpings(soup),
88
- }
89
- elif role.lower() == "fielder":
90
- stats = {
91
- "catches": extract_fielder_catches(soup),
92
- "direct_runouts": extract_direct_runouts(soup),
93
- }
94
  else:
95
- stats = {"error": "Invalid role specified"}
96
-
97
- return stats
98
-
99
  except Exception as e:
100
- return {"error": f"Error scraping data: {str(e)}"}
101
-
102
-
103
- def format_analysis(player_name, role, player_details, detailed_stats):
104
- return f"""
105
- Cricketer: {player_name}
106
- Role: {role}
107
- Country: {player_details.get('country', 'Unknown')}
108
- Batting Style: {player_details.get('battingStyle', 'Unknown')}
109
- Bowling Style: {player_details.get('bowlingStyle', 'Unknown')}
110
-
111
- Recent Performance:
112
- {detailed_stats}
113
- """
114
 
115
  # Initialize tools
116
  final_answer = FinalAnswerTool()
@@ -143,6 +79,3 @@ if __name__ == "__main__":
143
 
144
 
145
 
146
- # 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:
147
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
148
-
 
4
  import yaml
5
  import os
6
  from typing import Dict, Union
7
+
8
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
9
  from tools.final_answer import FinalAnswerTool
10
  from Gradio_UI import GradioUI
11
 
12
+ import time
13
+
14
+
15
+
16
  HF_TOKEN = os.getenv("HF_TOKEN", "default_hf_token_if_not_found")
 
17
 
18
+
19
  @tool
20
+ def get_weather(city: str) -> str:
21
+ """Fetches the current weather for a specified city using Open-Meteo API (No API Key Needed).
22
  Args:
23
+ city: The name of the city.
 
24
  """
25
  try:
26
+ # Get city coordinates from Open-Meteo's geocoding API
27
+ geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1"
28
+ geo_response = requests.get(geo_url)
 
 
 
 
29
 
30
+ if geo_response.status_code == 200 and geo_response.json().get("results"):
31
+ city_data = geo_response.json()["results"][0]
32
+ lat, lon = city_data["latitude"], city_data["longitude"]
33
+ else:
34
+ return f"Error: Unable to find location for '{city}'."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # Fetch weather data
37
+ weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
38
+ weather_response = requests.get(weather_url)
39
 
40
+ if weather_response.status_code == 200:
41
+ weather_data = weather_response.json()["current_weather"]
42
+ temp = weather_data["temperature"]
43
+ wind_speed = weather_data["windspeed"]
44
+ return f"Weather in {city}: Temp: {temp}°C, Wind Speed: {wind_speed} m/s"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  else:
46
+ return "Error fetching weather data."
47
+
 
 
48
  except Exception as e:
49
+ return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  # Initialize tools
52
  final_answer = FinalAnswerTool()
 
79
 
80
 
81