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()