Files changed (1) hide show
  1. app.py +52 -2
app.py CHANGED
@@ -2,14 +2,64 @@ import gradio as gr
2
  import requests
3
  import json
4
  import os
 
 
 
 
5
  import pandas as pd
6
 
7
  BASE_URL = "https://api.jigsawstack.com/v1"
8
  headers = {
9
- "x-api-key": os.getenv("JIGSAWSTACK_API_KEY")
10
  }
11
 
12
- def analyze_sentiment(text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  if not text or not text.strip():
14
  return "Error: Text input is required.", None, None, None, None
15
 
 
2
  import requests
3
  import json
4
  import os
5
+ import time
6
+ from collections import defaultdict
7
+ from PIL import Image
8
+ import io
9
  import pandas as pd
10
 
11
  BASE_URL = "https://api.jigsawstack.com/v1"
12
  headers = {
13
+ "x-api-key":os.getenv("JIGSAWSTACK_API_KEY")
14
  }
15
 
16
+
17
+ # Rate limiting configuration
18
+ request_times = defaultdict(list)
19
+ MAX_REQUESTS = 1 # Maximum requests per time window
20
+ TIME_WINDOW = 3600 # Time window in seconds (1 hour)
21
+
22
+ def get_real_ip(request: gr.Request):
23
+ """Extract real IP address using x-forwarded-for header or fallback"""
24
+ if not request:
25
+ return "unknown"
26
+
27
+ forwarded = request.headers.get("x-forwarded-for")
28
+ if forwarded:
29
+ ip = forwarded.split(",")[0].strip() # First IP in the list is the client's
30
+ else:
31
+ ip = request.client.host # fallback
32
+ return ip
33
+
34
+ def check_rate_limit(request: gr.Request):
35
+ """Check if the current request exceeds rate limits"""
36
+ if not request:
37
+ return True, "Rate limit check failed - no request info"
38
+
39
+ ip = get_real_ip(request)
40
+ now = time.time()
41
+
42
+ # Clean up old timestamps outside the time window
43
+ request_times[ip] = [t for t in request_times[ip] if now - t < TIME_WINDOW]
44
+
45
+
46
+ # Check if rate limit exceeded
47
+ if len(request_times[ip]) >= MAX_REQUESTS:
48
+ time_remaining = int(TIME_WINDOW - (now - request_times[ip][0]))
49
+ time_remaining_minutes = round(time_remaining / 60, 1)
50
+ time_window_minutes = round(TIME_WINDOW / 60, 1)
51
+
52
+ return False, f"Rate limit exceeded. You can make {MAX_REQUESTS} requests per {time_window_minutes} minutes. Try again in {time_remaining_minutes} minutes."
53
+
54
+ # Add current request timestamp
55
+ request_times[ip].append(now)
56
+ return True, ""
57
+
58
+ def analyze_sentiment(text, request: gr.Request):
59
+ rate_limit_ok, rate_limit_msg = check_rate_limit(request)
60
+ if not rate_limit_ok:
61
+ return f"❌ {rate_limit_msg}", None, None, None, None
62
+
63
  if not text or not text.strip():
64
  return "Error: Text input is required.", None, None, None, None
65