mgokg commited on
Commit
0dd3fa8
·
verified ·
1 Parent(s): 435b9aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +209 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deutsche Bahn Timetable Gradio App
2
+
3
+ ## app.py
4
+
5
+ ```python
6
+ import gradio as gr
7
+ import requests
8
+ from datetime import datetime
9
+ import xml.etree.ElementTree as ET
10
+
11
+ # EVA-Nummern für Hauptbahnhöfe
12
+ STATION_EVA = {
13
+ 'frankfurt': '8000105',
14
+ 'berlin': '8011160',
15
+ 'münchen': '8000261',
16
+ 'hamburg': '8002549',
17
+ 'köln': '8000207',
18
+ 'stuttgart': '8000096',
19
+ 'düsseldorf': '8000085',
20
+ 'dortmund': '8000080',
21
+ 'essen': '8000098',
22
+ 'leipzig': '8010205',
23
+ 'bremen': '8000050',
24
+ 'dresden': '8010085',
25
+ 'hannover': '8000152',
26
+ 'nürnberg': '8000284',
27
+ 'duisburg': '8000086',
28
+ }
29
+
30
+ def get_eva_number(station_name):
31
+ """Wandelt Stationsnamen in EVA-Nummer um"""
32
+ normalized = station_name.lower().strip()
33
+ return STATION_EVA.get(normalized)
34
+
35
+ def search_connections(departure, destination, client_id, api_key):
36
+ """Sucht Verbindungen zwischen zwei Bahnhöfen"""
37
+
38
+ if not departure or not destination:
39
+ return "❌ Bitte Abfahrts- und Zielort eingeben"
40
+
41
+ if not client_id or not api_key:
42
+ return "❌ Bitte Client ID und API Key eingeben"
43
+
44
+ # EVA-Nummer für Abfahrtsort ermitteln
45
+ departure_eva = get_eva_number(departure)
46
+ if not departure_eva:
47
+ available = ', '.join(STATION_EVA.keys())
48
+ return f"❌ Station '{departure}' nicht gefunden.\n\nVerfügbare Stationen: {available}"
49
+
50
+ # Aktuelles Datum und Stunde
51
+ now = datetime.now()
52
+ datum = now.strftime("%y%m%d") # YYMMDD
53
+ stunde = now.strftime("%H") # HH
54
+
55
+ # API-Aufruf
56
+ url = f"https://apis.deutschebahn.com/db-api-marketplace/apis/timetables/v1/plan/{departure_eva}/{datum}/{stunde}"
57
+
58
+ headers = {
59
+ "DB-Client-Id": client_id,
60
+ "DB-Api-Key": api_key,
61
+ "accept": "application/xml"
62
+ }
63
+
64
+ try:
65
+ response = requests.get(url, headers=headers, timeout=10)
66
+
67
+ if response.status_code != 200:
68
+ return f"❌ API Fehler: {response.status_code} - {response.text[:200]}"
69
+
70
+ # XML parsen
71
+ root = ET.fromstring(response.content)
72
+ connections = []
73
+
74
+ # Alle Züge durchgehen
75
+ for train in root.findall('.//s'):
76
+ # Abfahrtsinformationen
77
+ dp = train.find('dp')
78
+ if dp is None:
79
+ continue
80
+
81
+ # Route des Zugs
82
+ path = dp.get('ppth', '')
83
+
84
+ # Prüfen ob Zielort in Route enthalten ist
85
+ if destination.lower() in path.lower():
86
+ train_id = train.get('id', 'Unbekannt')
87
+ planned_time = dp.get('pt', '')
88
+ platform = dp.get('pp', 'n/a')
89
+
90
+ # Zeit formatieren (von HHMM zu HH:MM)
91
+ if len(planned_time) == 4:
92
+ planned_time = f"{planned_time[:2]}:{planned_time[2:]}"
93
+
94
+ # Route formatieren
95
+ route = ' → '.join(path.split('|'))
96
+
97
+ connections.append({
98
+ 'train': train_id,
99
+ 'time': planned_time,
100
+ 'platform': platform,
101
+ 'route': route
102
+ })
103
+
104
+ # Ergebnisse formatieren
105
+ if not connections:
106
+ return f"ℹ️ Keine direkten Verbindungen von {departure.title()} nach {destination.title()} gefunden.\n\nHinweis: Die App sucht nur nach direkten Verbindungen in der nächsten Stunde."
107
+
108
+ result = f"🚆 Verbindungen von {departure.title()} nach {destination.title()}\n"
109
+ result += f"📅 {now.strftime('%d.%m.%Y')} ab {now.strftime('%H:00')} Uhr\n\n"
110
+
111
+ for i, conn in enumerate(connections[:10], 1):
112
+ result += f"─────────────────────────────────\n"
113
+ result += f"{i}. {conn['train']}\n"
114
+ result += f" ⏰ Abfahrt: {conn['time']} Uhr\n"
115
+ result += f" 🚉 Gleis: {conn['platform']}\n"
116
+ result += f" 🗺️ Route: {conn['route']}\n\n"
117
+
118
+ return result
119
+
120
+ except requests.exceptions.Timeout:
121
+ return "❌ Zeitüberschreitung bei der API-Anfrage"
122
+ except requests.exceptions.RequestException as e:
123
+ return f"❌ Netzwerkfehler: {str(e)}"
124
+ except ET.ParseError as e:
125
+ return f"❌ Fehler beim Parsen der XML-Antwort: {str(e)}"
126
+ except Exception as e:
127
+ return f"❌ Unerwarteter Fehler: {str(e)}"
128
+
129
+ # Gradio Interface erstellen
130
+ with gr.Blocks(title="Deutsche Bahn Fahrplanauskunft", theme=gr.themes.Soft()) as demo:
131
+ gr.Markdown(
132
+ """
133
+ # 🚆 Deutsche Bahn Fahrplanauskunft
134
+ Finden Sie Zugverbindungen mit der DB Timetable API
135
+ """
136
+ )
137
+
138
+ with gr.Row():
139
+ with gr.Column():
140
+ client_id_input = gr.Textbox(
141
+ label="DB Client ID",
142
+ placeholder="Ihre Client ID von developers.deutschebahn.com",
143
+ type="password"
144
+ )
145
+ api_key_input = gr.Textbox(
146
+ label="DB API Key",
147
+ placeholder="Ihr API Key",
148
+ type="password"
149
+ )
150
+
151
+ with gr.Row():
152
+ with gr.Column():
153
+ departure_input = gr.Textbox(
154
+ label="Abfahrtsort",
155
+ placeholder="z.B. Frankfurt",
156
+ value=""
157
+ )
158
+ with gr.Column():
159
+ destination_input = gr.Textbox(
160
+ label="Zielort",
161
+ placeholder="z.B. Berlin",
162
+ value=""
163
+ )
164
+
165
+ gr.Markdown("⏰ **Abfahrtszeit:** Jetzt (automatisch)")
166
+
167
+ search_button = gr.Button("🔍 Verbindungen suchen", variant="primary", size="lg")
168
+
169
+ output = gr.Textbox(
170
+ label="Ergebnisse",
171
+ lines=20,
172
+ max_lines=30
173
+ )
174
+
175
+ gr.Markdown(
176
+ f"""
177
+ ### 📍 Verfügbare Stationen
178
+ {', '.join(sorted(STATION_EVA.keys()))}
179
+
180
+ ### ℹ️ Hinweise
181
+ - Sie benötigen einen kostenlosen API-Zugang von [DB API Marketplace](https://developers.deutschebahn.com)
182
+ - Die App sucht nach direkten Verbindungen in der aktuellen Stunde
183
+ - Geben Sie Städtenamen ohne "Hbf" ein (z.B. "Frankfurt" statt "Frankfurt Hbf")
184
+ """
185
+ )
186
+
187
+ search_button.click(
188
+ fn=search_connections,
189
+ inputs=[departure_input, destination_input, client_id_input, api_key_input],
190
+ outputs=output
191
+ )
192
+
193
+ if __name__ == "__main__":
194
+ demo.launch()
195
+ ```
196
+
197
+ ## requirements.txt
198
+
199
+ ```
200
+ gradio
201
+ requests
202
+ ```
203
+
204
+ ## Installation und Verwendung
205
+
206
+ 1. Erstellen Sie diese beiden Dateien in Ihrem Hugging Face Space
207
+ 2. Die App startet automatisch
208
+ 3. Holen Sie sich API-Zugangsdaten von [developers.deutschebahn.com](https://developers.deutschebahn.com)
209
+ 4. Geben Sie die Zugangsdaten ein und suchen Sie nach Verbindungen