File size: 2,763 Bytes
4bd31a2
 
 
 
8a6b073
4bd31a2
 
 
 
8a6b073
4bd31a2
8a6b073
4bd31a2
 
8a6b073
 
 
 
4bd31a2
 
8a6b073
 
 
4bd31a2
8a6b073
 
 
 
4bd31a2
8a6b073
 
 
 
 
 
 
 
 
 
 
 
 
 
4bd31a2
8a6b073
 
 
 
 
 
 
 
 
 
 
 
 
4bd31a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f06084
8a6b073
4bd31a2
8a6b073
4bd31a2
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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)