Spaces:
Paused
Paused
Commit
·
7b58805
1
Parent(s):
657c17b
nes
Browse files- Dockerfile +1 -1
- client.py +36 -44
- main.py +69 -24
Dockerfile
CHANGED
@@ -19,4 +19,4 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|
19 |
|
20 |
COPY --chown=user . .
|
21 |
|
22 |
-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
19 |
|
20 |
COPY --chown=user . .
|
21 |
|
22 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--client-max-size", "10485760"]
|
client.py
CHANGED
@@ -1,61 +1,53 @@
|
|
1 |
-
import
|
2 |
import base64
|
3 |
import json
|
4 |
-
import requests
|
5 |
-
from PIL import Image
|
6 |
import urllib3
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
orig_path = r"D:\grcpsample\content\extracted\images_8184456bc26d4e7f9c5237c350fe20ba\page_4.png"
|
11 |
-
resized_path = r"D:\grcpsample\content\extracted\images_8184456bc26d4e7f9c5237c350fe20ba\page_4_small.jpg"
|
12 |
-
|
13 |
-
# 1. Load and downscale
|
14 |
-
img = Image.open(orig_path)
|
15 |
-
max_side = 800 # tweak to 600 or 512 if still too large
|
16 |
-
scale = max_side / max(img.size)
|
17 |
-
if scale < 1.0:
|
18 |
-
new_size = (int(img.width * scale), int(img.height * scale))
|
19 |
-
img = img.resize(new_size, Image.LANCZOS)
|
20 |
-
|
21 |
-
# 2. Save as JPEG at 70% quality
|
22 |
-
img.save(resized_path, format="JPEG", quality=70)
|
23 |
|
24 |
-
|
25 |
-
new_size_kb = os.path.getsize(resized_path) / 1024
|
26 |
-
print(f"Resized JPEG size: {new_size_kb:.2f} KB") # aim for ≤ 500 KB
|
27 |
|
28 |
-
#
|
29 |
-
with open(
|
30 |
-
|
31 |
-
|
32 |
-
b64_kb = len(b64.encode("utf-8")) / 1024
|
33 |
-
print(f"Base64 size: {b64_kb:.2f} KB") # expect ~1.33× raw size
|
34 |
|
35 |
-
# 5. Build payload and measure final JSON
|
36 |
payload = {
|
37 |
"inputs": {
|
38 |
-
"image":
|
39 |
"question": "What is in the image?",
|
40 |
"stream": True
|
41 |
}
|
42 |
}
|
43 |
-
json_payload = json.dumps(payload)
|
44 |
-
final_kb = len(json_payload.encode("utf-8")) / 1024
|
45 |
-
print(f"Final JSON payload: {final_kb:.2f} KB") # want < ~700 KB
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
headers = {
|
|
|
|
|
50 |
|
51 |
try:
|
52 |
-
with requests.post(url, data=
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
raise
|
|
|
1 |
+
import requests
|
2 |
import base64
|
3 |
import json
|
|
|
|
|
4 |
import urllib3
|
5 |
|
6 |
+
# url = "https://llm-fastapi-sreejith8100.hf.space/predict"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
+
url = "https://sreejith8100-llm-fastapi.hf.space/predict"
|
|
|
|
|
9 |
|
10 |
+
# Read image bytes and encode as base64 string
|
11 |
+
with open(r"D:\grcpsample\content\extracted\images_21f3b49d112546a5bbf39d66a2f9c6ac\page_4.png", "rb") as f:
|
12 |
+
image_bytes = f.read()
|
13 |
+
image_base64 = base64.b64encode(image_bytes).decode("utf-8")
|
|
|
|
|
14 |
|
|
|
15 |
payload = {
|
16 |
"inputs": {
|
17 |
+
"image": image_base64,
|
18 |
"question": "What is in the image?",
|
19 |
"stream": True
|
20 |
}
|
21 |
}
|
|
|
|
|
|
|
22 |
|
23 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
24 |
+
|
25 |
+
headers = {
|
26 |
+
"Content-Type": "application/json"
|
27 |
+
}
|
28 |
|
29 |
try:
|
30 |
+
with requests.post(url, data=json.dumps(payload), headers=headers, stream=True, verify=False) as response:
|
31 |
+
response.raise_for_status() # Raise error for HTTP errors
|
32 |
+
|
33 |
+
for line in response.iter_lines():
|
34 |
+
if line:
|
35 |
+
decoded_line = line.decode("utf-8")
|
36 |
+
if decoded_line.startswith("data: "):
|
37 |
+
content = decoded_line.replace("data: ", "")
|
38 |
+
try:
|
39 |
+
parsed = json.loads(content)
|
40 |
+
except json.JSONDecodeError as e:
|
41 |
+
raise ValueError(f"Malformed JSON chunk: {content}") from e
|
42 |
+
|
43 |
+
output = parsed.get("output", "")
|
44 |
+
if output:
|
45 |
+
print(output, end="", flush=True)
|
46 |
+
|
47 |
+
except requests.HTTPError as http_err:
|
48 |
+
print(f"HTTP error occurred: {http_err}")
|
49 |
+
raise
|
50 |
+
|
51 |
+
except Exception as err:
|
52 |
+
print(f"Error occurred: {err}")
|
53 |
raise
|
main.py
CHANGED
@@ -1,50 +1,95 @@
|
|
1 |
-
from fastapi import FastAPI
|
2 |
from fastapi.responses import JSONResponse, StreamingResponse
|
3 |
-
from
|
4 |
-
import
|
5 |
-
import json
|
6 |
-
|
7 |
-
from endpoint_handler import EndpointHandler # your handler file
|
8 |
|
|
|
9 |
app = FastAPI()
|
10 |
|
|
|
11 |
handler = None
|
12 |
|
13 |
@app.on_event("startup")
|
14 |
async def load_handler():
|
15 |
global handler
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
class PredictInput(BaseModel):
|
19 |
-
image: str
|
20 |
question: str
|
21 |
stream: bool = False
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
class PredictRequest(BaseModel):
|
24 |
inputs: PredictInput
|
25 |
|
26 |
-
@app.get("/")
|
27 |
-
async def root():
|
28 |
-
return {"message": "FastAPI app is running on Hugging Face"}
|
29 |
-
|
30 |
@app.post("/predict")
|
31 |
async def predict_endpoint(payload: PredictRequest):
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
35 |
"inputs": {
|
36 |
"image": payload.inputs.image,
|
37 |
"question": payload.inputs.question,
|
38 |
-
"stream": payload.inputs.stream
|
39 |
}
|
40 |
}
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
if isinstance(result, types.GeneratorType):
|
45 |
-
def event_stream():
|
46 |
-
|
47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
49 |
-
|
50 |
-
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, UploadFile, File, Form, BackgroundTasks
|
2 |
from fastapi.responses import JSONResponse, StreamingResponse
|
3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
4 |
+
from pydantic import BaseModel, validator
|
5 |
+
import base64, types, json, logging, asyncio
|
6 |
+
from endpoint_handler import EndpointHandler
|
|
|
7 |
|
8 |
+
logger = logging.getLogger("uvicorn.error")
|
9 |
app = FastAPI()
|
10 |
|
11 |
+
|
12 |
handler = None
|
13 |
|
14 |
@app.on_event("startup")
|
15 |
async def load_handler():
|
16 |
global handler
|
17 |
+
try:
|
18 |
+
handler = EndpointHandler()
|
19 |
+
logger.info("EndpointHandler initialized successfully.")
|
20 |
+
except Exception as e:
|
21 |
+
logger.error(f"Failed to initialize handler: {e}", exc_info=True)
|
22 |
+
handler = None # so /predict will return 503
|
23 |
+
|
24 |
+
@app.on_event("shutdown")
|
25 |
+
async def cleanup_handler():
|
26 |
+
if handler:
|
27 |
+
try:
|
28 |
+
handler.close()
|
29 |
+
logger.info("Handler cleaned up on shutdown.")
|
30 |
+
except Exception:
|
31 |
+
logger.error("Error during handler cleanup", exc_info=True)
|
32 |
|
33 |
class PredictInput(BaseModel):
|
34 |
+
image: str
|
35 |
question: str
|
36 |
stream: bool = False
|
37 |
|
38 |
+
@validator("question")
|
39 |
+
def question_not_empty(cls, v):
|
40 |
+
if not v.strip():
|
41 |
+
raise ValueError("Question must not be empty")
|
42 |
+
return v
|
43 |
+
|
44 |
+
@validator("image")
|
45 |
+
def valid_base64(cls, v):
|
46 |
+
try:
|
47 |
+
base64.b64decode(v, validate=True)
|
48 |
+
except Exception:
|
49 |
+
raise ValueError("`image` must be valid base64")
|
50 |
+
return v
|
51 |
+
|
52 |
class PredictRequest(BaseModel):
|
53 |
inputs: PredictInput
|
54 |
|
|
|
|
|
|
|
|
|
55 |
@app.post("/predict")
|
56 |
async def predict_endpoint(payload: PredictRequest):
|
57 |
+
if handler is None:
|
58 |
+
return JSONResponse({"error": "Service unavailable"}, status_code=503)
|
59 |
+
|
60 |
+
# Log input
|
61 |
+
logger.info(f"Received question: {payload.inputs.question}")
|
62 |
+
|
63 |
+
# Prepare the data dict exactly how EndpointHandler expects
|
64 |
+
request_dict = {
|
65 |
"inputs": {
|
66 |
"image": payload.inputs.image,
|
67 |
"question": payload.inputs.question,
|
68 |
+
"stream": payload.inputs.stream,
|
69 |
}
|
70 |
}
|
71 |
+
|
72 |
+
try:
|
73 |
+
result = await asyncio.to_thread(handler.predict, request_dict)
|
74 |
+
except ValueError as ve:
|
75 |
+
return JSONResponse({"error": str(ve)}, status_code=400)
|
76 |
+
except Exception as e:
|
77 |
+
logger.error("Unexpected error in handler.predict", exc_info=True)
|
78 |
+
return JSONResponse({"error": "Internal server error"}, status_code=500)
|
79 |
+
|
80 |
+
# If handler.predict returned a generator, wrap in SSE
|
81 |
if isinstance(result, types.GeneratorType):
|
82 |
+
async def event_stream():
|
83 |
+
try:
|
84 |
+
for chunk in result:
|
85 |
+
yield f"data: {json.dumps(chunk)}\n\n"
|
86 |
+
except (asyncio.CancelledError, ConnectionResetError):
|
87 |
+
logger.info("Client disconnected from stream.")
|
88 |
+
except Exception:
|
89 |
+
logger.error("Error during streaming", exc_info=True)
|
90 |
+
yield f"data: {json.dumps({'error': 'Stream error'})}\n\n"
|
91 |
+
|
92 |
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
93 |
+
|
94 |
+
# Otherwise normal JSON
|
95 |
+
return JSONResponse(content=result, status_code=200)
|