jborelo commited on
Commit
5c45d55
·
verified ·
1 Parent(s): bc8e4e9

Update get_next_trains_krakow_to_warszawa to use PKP Intercity API

Browse files
Files changed (1) hide show
  1. app.py +89 -31
app.py CHANGED
@@ -34,47 +34,105 @@ def get_friends_names(name:str, maxnb: int)-> List[str]: #it's import to specify
34
 
35
  @tool
36
  def get_next_trains_krakow_to_warszawa(count: int = 5) -> List[dict]:
37
- """A tool that returns the next train departures from Krakow to Warszawa
38
  Args:
39
  count: number of train departures to return (default is 5)
40
  """
41
  try:
42
- # Mock data for train schedules (in a real scenario, you would use PKP API or scraping)
43
- # This is example data showing typical train routes
44
- base_trains = [
45
- {"train": "TLK 15100", "departure": "06:10", "arrival": "08:55"},
46
- {"train": "EIP 1500", "departure": "07:00", "arrival": "09:28"},
47
- {"train": "EIC 1502", "departure": "08:00", "arrival": "10:25"},
48
- {"train": "TLK 15102", "departure": "09:10", "arrival": "11:55"},
49
- {"train": "EIP 1504", "departure": "10:00", "arrival": "12:28"},
50
- {"train": "TLK 15104", "departure": "11:10", "arrival": "13:55"},
51
- {"train": "EIC 1506", "departure": "12:00", "arrival": "14:25"},
52
- {"train": "TLK 15106", "departure": "13:10", "arrival": "15:55"},
53
- {"train": "EIP 1508", "departure": "14:00", "arrival": "16:28"},
54
- {"train": "TLK 15108", "departure": "15:10", "arrival": "17:55"},
55
- ]
 
 
 
 
 
56
 
57
- # Get current time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  current_time = datetime.datetime.now(pytz.timezone('Europe/Warsaw'))
59
- current_hour = current_time.hour
60
- current_minute = current_time.minute
61
 
62
- # Filter trains that haven't departed yet
63
- upcoming_trains = []
64
- for train in base_trains:
65
- dep_time = train["departure"].split(":")
66
- dep_hour = int(dep_time[0])
67
- dep_minute = int(dep_time[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- # Check if train hasn't departed yet
70
- if dep_hour > current_hour or (dep_hour == current_hour and dep_minute > current_minute):
71
- upcoming_trains.append(train)
 
 
 
 
 
 
 
 
72
 
73
- # If no more trains today, return trains for tomorrow
74
- if len(upcoming_trains) < count:
75
- upcoming_trains.extend(base_trains[:count - len(upcoming_trains)])
76
 
77
- return upcoming_trains[:count]
78
  except Exception as e:
79
  return [{"error": f"Failed to fetch train data: {str(e)}"}]
80
 
 
34
 
35
  @tool
36
  def get_next_trains_krakow_to_warszawa(count: int = 5) -> List[dict]:
37
+ """A tool that returns the next train departures from Krakow to Warszawa using PKP Intercity API
38
  Args:
39
  count: number of train departures to return (default is 5)
40
  """
41
  try:
42
+ # PKP Intercity API endpoint
43
+ # Station codes: Krakow Glowny = 5100069, Warszawa Centralna = 0000011
44
+ current_time = datetime.datetime.now(pytz.timezone('Europe/Warsaw'))
45
+ date_str = current_time.strftime('%Y-%m-%d')
46
+
47
+ # PKP Intercity API request
48
+ api_url = "https://bilety.intercity.pl/api/v3/Search/Connections"
49
+
50
+ headers = {
51
+ 'Content-Type': 'application/json',
52
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
53
+ }
54
+
55
+ payload = {
56
+ "departureStationCode": "5100069", # Krakow Glowny
57
+ "arrivalStationCode": "0000011", # Warszawa Centralna
58
+ "departureDate": date_str,
59
+ "passengers": [{"type": "ADULT", "count": 1}]
60
+ }
61
 
62
+ response = requests.post(api_url, json=payload, headers=headers, timeout=10)
63
+
64
+ if response.status_code == 200:
65
+ data = response.json()
66
+ trains = []
67
+
68
+ # Parse the response and extract train information
69
+ if 'connections' in data:
70
+ for connection in data['connections'][:count]:
71
+ train_info = {
72
+ 'train': connection.get('trainNumber', 'N/A'),
73
+ 'departure': connection.get('departureTime', 'N/A'),
74
+ 'arrival': connection.get('arrivalTime', 'N/A'),
75
+ 'duration': connection.get('duration', 'N/A'),
76
+ 'carrier': connection.get('carrier', 'PKP Intercity')
77
+ }
78
+ trains.append(train_info)
79
+
80
+ return trains if trains else [{"info": "No trains found for today"}]
81
+ else:
82
+ # Fallback to web scraping approach
83
+ return scrape_pkp_trains(count)
84
+ else:
85
+ # If API fails, try web scraping
86
+ return scrape_pkp_trains(count)
87
+
88
+ except Exception as e:
89
+ # Fallback to scraping if API fails
90
+ return scrape_pkp_trains(count)
91
+
92
+ def scrape_pkp_trains(count: int = 5) -> List[dict]:
93
+ """Fallback method to scrape PKP website for train data"""
94
+ try:
95
+ # Try alternative PKP portalpasazera.pl API
96
  current_time = datetime.datetime.now(pytz.timezone('Europe/Warsaw'))
 
 
97
 
98
+ # PortalPasazera API endpoint
99
+ api_url = "https://portalpasazera.pl/Ajax/QueryConnectionsEx"
100
+
101
+ headers = {
102
+ 'Content-Type': 'application/x-www-form-urlencoded',
103
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
104
+ }
105
+
106
+ # Format: station name or code
107
+ data = {
108
+ 'queryPageDisplayed': 'today',
109
+ 'Name': 'Kraków Główny',
110
+ 'NameDes': 'Warszawa Centralna',
111
+ 'Date': current_time.strftime('%d.%m.%Y'),
112
+ 'Hour': current_time.strftime('%H:%M')
113
+ }
114
+
115
+ response = requests.post(api_url, data=data, headers=headers, timeout=10)
116
+
117
+ if response.status_code == 200:
118
+ result = response.json()
119
+ trains = []
120
 
121
+ if 'Connections' in result:
122
+ for conn in result['Connections'][:count]:
123
+ train_info = {
124
+ 'train': conn.get('TrainName', 'N/A'),
125
+ 'departure': conn.get('DepartureTime', 'N/A'),
126
+ 'arrival': conn.get('ArrivalTime', 'N/A'),
127
+ 'carrier': conn.get('Carrier', 'N/A')
128
+ }
129
+ trains.append(train_info)
130
+
131
+ return trains if trains else [{"error": "No trains found"}]
132
 
133
+ # If all else fails, return error with live data attempt message
134
+ return [{"error": "Unable to fetch live train data. PKP API may be unavailable."}]
 
135
 
 
136
  except Exception as e:
137
  return [{"error": f"Failed to fetch train data: {str(e)}"}]
138