sathish2352 commited on
Commit
a2d05fd
·
verified ·
1 Parent(s): d65e50c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -32
app.py CHANGED
@@ -1,48 +1,63 @@
1
  # app.py
2
- from fastapi import FastAPI, Request, HTTPException
3
  from fastapi.responses import StreamingResponse
4
  import qrcode
5
  import io
 
6
 
7
  app = FastAPI()
8
 
9
- def stylize_text(text: str) -> str:
10
- """Return the text with alternating upper/lowercase characters (old behaviour)."""
11
- return text
12
-
13
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @app.post("/echo")
15
  async def echo(request: Request):
16
- """Accept JSON payload and respond with a QR‑code PNG encoding the stylised text."""
 
 
 
 
 
 
 
 
 
17
  try:
18
  payload = await request.json()
19
  except Exception:
20
  raise HTTPException(status_code=400, detail="Expected a JSON body")
21
 
22
- if not payload:
23
  raise HTTPException(status_code=400, detail="Payload cannot be empty")
24
 
25
- # Normalise input
26
- if isinstance(payload, str):
27
- raw_text = payload
28
- elif isinstance(payload, dict) and "text" in payload:
29
- raw_text = str(payload["text"])
30
- else:
31
- # Fallback: convert entire JSON object to string
32
- raw_text = str(payload)
33
-
34
- # Apply old alternating‑case transformation
35
- qr_text = stylize_text(raw_text)
36
-
37
- # Build QR‑code
38
- qr = qrcode.QRCode(box_size=10, border=4)
39
- qr.add_data(qr_text)
40
- qr.make(fit=True)
41
- img = qr.make_image(fill_color="black", back_color="white")
42
-
43
- # Send back PNG
44
- buffer = io.BytesIO()
45
- img.save(buffer, format="PNG")
46
- buffer.seek(0)
47
-
48
- return StreamingResponse(buffer, media_type="image/png")
 
1
  # app.py
2
+ from fastapi import FastAPI, HTTPException, Request
3
  from fastapi.responses import StreamingResponse
4
  import qrcode
5
  import io
6
+ from functools import lru_cache
7
 
8
  app = FastAPI()
9
 
10
+ # ---------------------------------------------------------------------------
11
+ # QRcode generation helper (cached)
12
+ # ---------------------------------------------------------------------------
13
+ @lru_cache(maxsize=512)
14
+ def _qr_png(text: str) -> bytes:
15
+ """Return PNG bytes for *text*.
16
+
17
+ * Uses `qrcode.make`, which is faster than constructing a `QRCode` object
18
+ manually.
19
+ * Memoised with `lru_cache` so repeated requests for the same text are
20
+ served from memory (~10× faster, avoids QR code re‑creation and pillow
21
+ image encoding).
22
+ """
23
+ img = qrcode.make(text) # Fast 1‑liner QR generation
24
+ buf = io.BytesIO()
25
+ img.save(buf, format="PNG")
26
+ return buf.getvalue()
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # API endpoint
31
+ # ---------------------------------------------------------------------------
32
  @app.post("/echo")
33
  async def echo(request: Request):
34
+ """Generate a QR‑code for the given JSON body.
35
+
36
+ Accepted payloads:
37
+ • Plain JSON string → "Hello"
38
+ • Object with `text` → {"text": "Hello"}
39
+ Any other JSON types are stringified via `str(payload)`.
40
+ """
41
+ # ---------------------------------------------------------------------
42
+ # 1. Extract JSON body
43
+ # ---------------------------------------------------------------------
44
  try:
45
  payload = await request.json()
46
  except Exception:
47
  raise HTTPException(status_code=400, detail="Expected a JSON body")
48
 
49
+ if payload in (None, "", []):
50
  raise HTTPException(status_code=400, detail="Payload cannot be empty")
51
 
52
+ # Normalise to string
53
+ text = payload["text"] if isinstance(payload, dict) and "text" in payload else str(payload)
54
+
55
+ # ---------------------------------------------------------------------
56
+ # 2. Build / fetch QR code PNG (cached)
57
+ # ---------------------------------------------------------------------
58
+ png_bytes = _qr_png(text)
59
+
60
+ # ---------------------------------------------------------------------
61
+ # 3. Return as stream (new BytesIO per request so multiple clients can read)
62
+ # ---------------------------------------------------------------------
63
+ return StreamingResponse(io.BytesIO(png_bytes), media_type="image/png")