DurgaDeepak commited on
Commit
760be27
·
verified ·
1 Parent(s): 595fad2

Create helpers.py

Browse files
Files changed (1) hide show
  1. utils/helpers.py +42 -0
utils/helpers.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ import time
3
+ import logging
4
+ import socket
5
+ import ipaddress
6
+ from urllib.parse import urlparse
7
+ import gradio as gr
8
+
9
+
10
+
11
+ # Helper Functions
12
+ def format_error(message):
13
+ """Formats error messages for consistent user feedback."""
14
+ return {"error": message}
15
+
16
+ def toggle_visibility(show, *components):
17
+ """Toggles visibility for multiple Gradio components."""
18
+ return [gr.update(visible=show) for _ in components]
19
+
20
+ def generate_session_id():
21
+ """Generates a unique session ID for tracking inputs."""
22
+ return str(uuid.uuid4())
23
+
24
+ def log_runtime(start_time):
25
+ """Logs the runtime of a process."""
26
+ elapsed_time = time.time() - start_time
27
+ logger.info(f"Process completed in {elapsed_time:.2f} seconds.")
28
+ return elapsed_time
29
+
30
+ def is_public_ip(url):
31
+ """
32
+ Checks whether the resolved IP address of a URL is public (non-local).
33
+ Prevents SSRF by blocking internal addresses like 127.0.0.1 or 192.168.x.x.
34
+ """
35
+ try:
36
+ hostname = urlparse(url).hostname
37
+ ip = socket.gethostbyname(hostname)
38
+ ip_obj = ipaddress.ip_address(ip)
39
+ return ip_obj.is_global # Only allow globally routable IPs
40
+ except Exception as e:
41
+ logger.warning(f"URL IP validation failed: {e}")
42
+ return False