File size: 1,489 Bytes
e519538
9c2f8b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e519538
 
9c2f8b0
4a4216c
9c2f8b0
 
d558a8c
9c2f8b0
 
 
 
 
 
 
 
621bfc1
 
9c2f8b0
621bfc1
9c2f8b0
 
 
 
e519538
621bfc1
e519538
 
9c2f8b0
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
import gradio as gr
import requests
import pytz
from datetime import datetime

def ts_to_str(timestamp, timezone):
    # Create a timezone-aware datetime object from the UNIX timestamp
    dt = datetime.fromtimestamp(timestamp, pytz.utc)

    # Convert the timezone-aware datetime object to the target timezone
    target_timezone = pytz.timezone(timezone)
    localized_dt = dt.astimezone(target_timezone)

    # Format the datetime object to the specified string format
    return localized_dt.strftime('%Y-%m-%d %H:%M:%S (%Z)')
    

def predict(text, request: gr.Request):
    # Get the IP address from the request object
    ip_address = request.headers.get('x-forwarded-for', request.client.host)
    
    # Call the WorldTimeAPI to get the timezone for the user's IP address
    response = requests.get(f'https://worldtimeapi.org/api/ip/{ip_address}')
    time_data = response.json()
    
    # Extract the timezone from the API response
    timezone_str = time_data.get('timezone', 'UTC')
    
    # Get the current timestamp and convert it to the user's local time
    timestamp = datetime.now().timestamp()
    current_time_local = ts_to_str(timestamp, timezone_str)

    import pdb; pdb.set_trace()
    
    info = {
        "ip": ip_address,
        "user_agent": request.headers["user-agent"],
        "current_time_local": current_time_local,
        "timezone": timezone_str
    }
    return info

demo = gr.Interface(fn=predict, inputs="text", outputs="json")
demo.launch()