Spaces:
Running
Running
import gradio as gr | |
import requests | |
from datetime import datetime, timedelta | |
from typing import Dict | |
import json | |
# Cache: { "YYYY-MM-DD": {...} } | |
color_cache: Dict[str, dict] = {} | |
def jour_tempo(day: str) -> str: | |
""" | |
Retrieves the EDF Tempo color for a given day. | |
Parameters: | |
day (str): | |
- 'today' for the current day | |
- 'tomorrow' for the next day | |
- a date in 'YYYY-MM-DD' format (e.g., '2024-06-01') | |
Returns: | |
str: | |
- A prettified JSON string containing the Tempo color and related information for the requested day. | |
- In case of error, returns a string starting with "Error: ...". | |
Handled exceptions: | |
- ValueError: if the date format is invalid | |
- requests.HTTPError: if the HTTP request fails | |
- Exception: for any other unexpected error | |
Example usage: | |
>>> jour_tempo('today') | |
'{\n "dateJour": "2024-06-01",\n "codeJour": "BLEU", ... }' | |
>>> jour_tempo('2024-06-01') | |
'{\n "dateJour": "2024-06-01",\n "codeJour": "BLANC", ... }' | |
>>> jour_tempo('2024-13-01') | |
'Error: Invalid date format. Use 'YYYY-MM-DD'.' | |
""" | |
try: | |
iso_day = formatted_day(day) | |
if iso_day in color_cache: | |
cached_data = color_cache[iso_day] | |
print(f"Retrieved cached data {cached_data}") | |
return json.dumps(cached_data, indent=2, ensure_ascii=False) | |
url = f"https://www.api-couleur-tempo.fr/api/jourTempo/{iso_day}" | |
response = requests.get(url, timeout=5) | |
response.raise_for_status() | |
data = response.json() | |
color_cache[iso_day] = data | |
print(f"Retrieved remote data {data}") | |
return json.dumps(data, indent=2, ensure_ascii=False) | |
except ValueError as ve: | |
return f"Error: {str(ve)}" | |
except requests.HTTPError as he: | |
return f"Error: {str(he)}" | |
except Exception as e: | |
return f"Error: {str(e)}" | |
def formatted_day(day: str) -> str: | |
if day == "today": | |
return datetime.today().date().isoformat() | |
elif day == "tomorrow": | |
return (datetime.today().date() + timedelta(days=1)).isoformat() | |
else: | |
try: | |
datetime.strptime(day, "%Y-%m-%d") | |
except ValueError: | |
raise ValueError("Invalid date format. Use 'YYYY-MM-DD'.") | |
return day | |
demo = gr.Interface( | |
fn=jour_tempo, | |
inputs=[gr.DateTime(value=datetime.today(), label="Jour", include_time=False, type="datetime")], | |
outputs=gr.Textbox(label="Résultat"), | |
title="Jour Tempo", | |
description="Couleur Tempo EDF pour 'today', 'tomorrow' ou n'importe quel jour au format 'YYYY-MM-DD'." | |
) | |
if __name__ == "__main__": | |
demo.launch(mcp_server=True) | |