LexTechA commited on
Commit
a3e5155
Β·
verified Β·
1 Parent(s): 30f0c4b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -24
app.py CHANGED
@@ -8,12 +8,13 @@ import numpy as np
8
  from contextlib import asynccontextmanager
9
  from datetime import datetime, timezone
10
 
 
 
11
  from fastapi import FastAPI, HTTPException, Security, Depends, Request
12
  from fastapi.security.api_key import APIKeyHeader
13
  from fastapi.middleware.cors import CORSMiddleware
14
  from pydantic import BaseModel
15
  from PIL import Image
16
- import torch
17
  import onnxruntime as rt
18
 
19
  from utils.tokenizer_base import Tokenizer
@@ -34,10 +35,19 @@ MODEL_PATH = "./model/model.onnx"
34
  ORT_INTRA_THREADS = int(os.getenv("ORT_INTRA_THREADS", "1"))
35
  ORT_INTER_THREADS = int(os.getenv("ORT_INTER_THREADS", "1"))
36
 
37
- # ── Torch global optimizations ────────────────────────────────────────────────
38
- torch.set_grad_enabled(False)
39
- torch.set_num_threads(1)
40
- torch.set_num_interop_threads(1)
 
 
 
 
 
 
 
 
 
41
 
42
  # ── API Key Auth ──────────────────────────────────────────────────────────────
43
  api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
@@ -47,6 +57,27 @@ def verify_key(key: str = Security(api_key_header)):
47
  raise HTTPException(status_code=401, detail="Invalid or missing API key")
48
  return key
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # ── Load model ────────────────────────────────────────────────────────────────
51
  logger.info("Loading ONNX model...")
52
  tokenizer = Tokenizer(VOCAB)
@@ -68,9 +99,6 @@ session = rt.InferenceSession(
68
  input_name = session.get_inputs()[0].name
69
  logger.info("βœ… ONNX model ready")
70
 
71
- # ── Request counter (per worker) ──────────────────────────────────────────────
72
- request_count = 0
73
-
74
  # ── Inference ─────────────────────────────────────────────────────────────────
75
  def preprocess(image: Image.Image) -> np.ndarray:
76
  image = image.convert("RGB").resize(IMG_SIZE, Image.BILINEAR)
@@ -80,9 +108,10 @@ def preprocess(image: Image.Image) -> np.ndarray:
80
 
81
 
82
  def solve_image(image: Image.Image) -> str:
83
- x = preprocess(image)
84
- logits = session.run(None, {input_name: x})[0]
85
- probs = torch.tensor(logits).softmax(-1)
 
86
  preds, _ = tokenizer.decode(probs)
87
  return preds[0]
88
 
@@ -115,7 +144,10 @@ class SolveResponse(BaseModel):
115
 
116
 
117
  # ── FastAPI ───────────────────────────────────────────────────────────────────
118
- app = FastAPI(title="CAPTCHA Solver API", lifespan=lifespan)
 
 
 
119
 
120
  app.add_middleware(
121
  CORSMiddleware,
@@ -125,7 +157,7 @@ app.add_middleware(
125
  )
126
 
127
 
128
- # ── Access logging middleware ─────���───────────────────────────────────────────
129
  @app.middleware("http")
130
  async def log_requests(request: Request, call_next):
131
  global request_count
@@ -133,15 +165,51 @@ async def log_requests(request: Request, call_next):
133
 
134
  timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
135
  ip = request.headers.get("X-Forwarded-For", request.client.host)
 
 
136
  req_num = request_count
137
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  start = time.time()
139
  response = await call_next(request)
140
  elapsed = time.time() - start
141
 
142
  logger.info(
143
- f"[#{req_num}] {timestamp} UTC | IP={ip} | "
144
- f"{request.method} {request.url.path} | {elapsed:.3f}s"
145
  )
146
 
147
  return response
@@ -151,18 +219,18 @@ async def log_requests(request: Request, call_next):
151
  @app.get("/health")
152
  def health():
153
  return {
154
- "status": "ok",
155
- "device": "cpu",
156
- "model": "ONNX INT8",
157
- "quantized": True,
158
- "workers": os.getenv("WEB_CONCURRENCY", "1"),
159
- "intra_threads": ORT_INTRA_THREADS,
160
  "requests_served": request_count,
161
  }
162
 
163
 
164
  @app.post("/solve-captcha-base64", response_model=SolveResponse)
165
- def solve(req: SolveRequest, _: str = Depends(verify_key)):
166
  start = time.time()
167
  try:
168
  raw = req.image_base64
@@ -172,13 +240,17 @@ def solve(req: SolveRequest, _: str = Depends(verify_key)):
172
  image = Image.open(io.BytesIO(base64.b64decode(raw)))
173
  text = solve_image(image).strip()[:5]
174
 
 
 
 
 
175
  elapsed = time.time() - start
176
  logger.info(f"βœ… Solved: '{text}' in {elapsed:.3f}s")
177
 
178
  return SolveResponse(success=True, text=text, processing_time=elapsed)
179
 
180
  except Exception as e:
181
- logger.error(f"Error: {e}")
182
  return SolveResponse(
183
  success=False,
184
  error=str(e),
 
8
  from contextlib import asynccontextmanager
9
  from datetime import datetime, timezone
10
 
11
+ import httpx
12
+ import asyncio
13
  from fastapi import FastAPI, HTTPException, Security, Depends, Request
14
  from fastapi.security.api_key import APIKeyHeader
15
  from fastapi.middleware.cors import CORSMiddleware
16
  from pydantic import BaseModel
17
  from PIL import Image
 
18
  import onnxruntime as rt
19
 
20
  from utils.tokenizer_base import Tokenizer
 
35
  ORT_INTRA_THREADS = int(os.getenv("ORT_INTRA_THREADS", "1"))
36
  ORT_INTER_THREADS = int(os.getenv("ORT_INTER_THREADS", "1"))
37
 
38
+ API_KEY = os.environ.get("API_KEY", "changeme")
39
+
40
+ # ── Security config ───────────────────────────────────────────────────────────
41
+ BURST_WINDOW = int(os.getenv("BURST_WINDOW", "5")) # seconds
42
+ BURST_MAX = int(os.getenv("BURST_MAX", "5")) # max requests in window
43
+
44
+ # Known paths β€” anything else is flagged as scanning
45
+ KNOWN_PATHS = {'/health', '/solve-captcha-base64', '/solve'}
46
+
47
+ # ── In-memory stores ──────────────────────────────────────────────────────────
48
+ _ip_activity: dict = {} # {ip: [timestamps]}
49
+ _ip_cache: dict = {} # {ip: {geo info}}
50
+ request_count = 0
51
 
52
  # ── API Key Auth ──────────────────────────────────────────────────────────────
53
  api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
 
57
  raise HTTPException(status_code=401, detail="Invalid or missing API key")
58
  return key
59
 
60
+ # ── IP geolocation β€” cached per IP ───────────────────────────────────────────
61
+ async def get_ip_info(ip: str) -> dict:
62
+ """
63
+ Lookup IP info via ip-api.com (free, no key needed).
64
+ Result cached so only first request per IP hits the external API.
65
+ Returns empty dict on failure β€” never blocks a request.
66
+ """
67
+ if ip in _ip_cache:
68
+ return _ip_cache[ip]
69
+ try:
70
+ async with httpx.AsyncClient(timeout=2.0) as client:
71
+ res = await client.get(
72
+ f"http://ip-api.com/json/{ip}",
73
+ params={"fields": "country,regionName,city,isp,org,proxy,hosting"}
74
+ )
75
+ info = res.json() if res.status_code == 200 else {}
76
+ except Exception:
77
+ info = {}
78
+ _ip_cache[ip] = info
79
+ return info
80
+
81
  # ── Load model ────────────────────────────────────────────────────────────────
82
  logger.info("Loading ONNX model...")
83
  tokenizer = Tokenizer(VOCAB)
 
99
  input_name = session.get_inputs()[0].name
100
  logger.info("βœ… ONNX model ready")
101
 
 
 
 
102
  # ── Inference ─────────────────────────────────────────────────────────────────
103
  def preprocess(image: Image.Image) -> np.ndarray:
104
  image = image.convert("RGB").resize(IMG_SIZE, Image.BILINEAR)
 
108
 
109
 
110
  def solve_image(image: Image.Image) -> str:
111
+ x = preprocess(image)
112
+ logits = session.run(None, {input_name: x})[0]
113
+ e = np.exp(logits - logits.max(axis=-1, keepdims=True))
114
+ probs = e / e.sum(axis=-1, keepdims=True)
115
  preds, _ = tokenizer.decode(probs)
116
  return preds[0]
117
 
 
144
 
145
 
146
  # ── FastAPI ───────────────────────────────────────────────────────────────────
147
+ app = FastAPI(
148
+ title="CAPTCHA Solver API",
149
+ lifespan=lifespan,
150
+ )
151
 
152
  app.add_middleware(
153
  CORSMiddleware,
 
157
  )
158
 
159
 
160
+ # ── Access + security monitoring middleware ───────────────────────────────────
161
  @app.middleware("http")
162
  async def log_requests(request: Request, call_next):
163
  global request_count
 
165
 
166
  timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
167
  ip = request.headers.get("X-Forwarded-For", request.client.host)
168
+ api_key = request.headers.get("X-API-Key", "none")
169
+ key_hint = api_key[:8] + "…" if len(api_key) > 8 else api_key
170
  req_num = request_count
171
+ path = request.url.path
172
+
173
+ # ── Unknown path β€” endpoint scanning ─────────────────────────────────────
174
+ if path not in KNOWN_PATHS:
175
+ logger.warning(
176
+ f"⚠️ UNKNOWN PATH | IP={ip} | {request.method} {path}"
177
+ )
178
+
179
+ # ── Burst detection ───────────────────────────────────────────────────────
180
+ now = time.time()
181
+ if ip not in _ip_activity:
182
+ _ip_activity[ip] = []
183
+ _ip_activity[ip] = [t for t in _ip_activity[ip] if now - t < BURST_WINDOW]
184
+ _ip_activity[ip].append(now)
185
+
186
+ if len(_ip_activity[ip]) > BURST_MAX:
187
+ logger.warning(
188
+ f"🚨 BURST DETECTED | IP={ip} | "
189
+ f"{len(_ip_activity[ip])} requests in {BURST_WINDOW}s"
190
+ )
191
+
192
+ # ── IP geolocation β€” cached, never blocks the request ────────────────────
193
+ info = await get_ip_info(ip)
194
+ country = info.get("country", "unknown")
195
+ isp = info.get("isp", "unknown")
196
+ is_proxy = info.get("proxy", False)
197
+ is_hosting = info.get("hosting", False)
198
+
199
+ if is_proxy or is_hosting:
200
+ logger.warning(
201
+ f"🚨 SUSPICIOUS IP | IP={ip} | country={country} | "
202
+ f"isp={isp} | proxy={is_proxy} | datacenter={is_hosting}"
203
+ )
204
+
205
+ # ── Process request ───────────────────────────────────────────────────────
206
  start = time.time()
207
  response = await call_next(request)
208
  elapsed = time.time() - start
209
 
210
  logger.info(
211
+ f"[#{req_num}] {timestamp} UTC | IP={ip} | country={country} | "
212
+ f"isp={isp} | key={key_hint} | {request.method} {path} | {elapsed:.3f}s"
213
  )
214
 
215
  return response
 
219
  @app.get("/health")
220
  def health():
221
  return {
222
+ "status": "ok",
223
+ "device": "cpu",
224
+ "model": "ONNX INT8",
225
+ "quantized": True,
226
+ "workers": os.getenv("WEB_CONCURRENCY", "1"),
227
+ "intra_threads": ORT_INTRA_THREADS,
228
  "requests_served": request_count,
229
  }
230
 
231
 
232
  @app.post("/solve-captcha-base64", response_model=SolveResponse)
233
+ async def solve(req: SolveRequest, _: str = Depends(verify_key)):
234
  start = time.time()
235
  try:
236
  raw = req.image_base64
 
240
  image = Image.open(io.BytesIO(base64.b64decode(raw)))
241
  text = solve_image(image).strip()[:5]
242
 
243
+ # Small delay before returning β€” avoids triggering rate limits
244
+ # on the target site from responses arriving too fast
245
+ await asyncio.sleep(0.84)
246
+
247
  elapsed = time.time() - start
248
  logger.info(f"βœ… Solved: '{text}' in {elapsed:.3f}s")
249
 
250
  return SolveResponse(success=True, text=text, processing_time=elapsed)
251
 
252
  except Exception as e:
253
+ logger.error(f"❌ Error: {e}")
254
  return SolveResponse(
255
  success=False,
256
  error=str(e),