BoooomNing commited on
Commit
7a343d8
Β·
verified Β·
1 Parent(s): a7b2061

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import base64
4
+ import time
5
+ import logging
6
+ from typing import Optional
7
+
8
+ import gradio as gr
9
+ from gradio_client import Client
10
+ from PIL import Image
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ HF_TOKEN = os.getenv("HF_TOKEN")
16
+ if not HF_TOKEN:
17
+ raise ValueError("HF_TOKEN environment variable is required")
18
+
19
+ backend_status = {
20
+ "client": None,
21
+ "connected": False,
22
+ "last_check": None,
23
+ "error_message": ""
24
+ }
25
+
26
+ def check_backend_connection():
27
+ """Check connection to SAKS backend"""
28
+ try:
29
+ test_client = Client("SnapwearAI/SAKS-backend", hf_token=HF_TOKEN)
30
+ backend_status.update({
31
+ "client": test_client,
32
+ "connected": True,
33
+ "error_message": "",
34
+ "last_check": time.time(),
35
+ })
36
+ logger.info("βœ… SAKS Backend connection established")
37
+ return True, "🟒 Backend is ready"
38
+ except Exception as e:
39
+ backend_status.update({
40
+ "client": None,
41
+ "connected": False,
42
+ "last_check": time.time(),
43
+ "error_message": str(e),
44
+ })
45
+ err = str(e).lower()
46
+ if "timeout" in err or "read operation timed out" in err:
47
+ return False, "🟑 Backend starting up..."
48
+ return False, f"πŸ”΄ Backend error: {e}"
49
+
50
+ check_backend_connection()
51
+
52
+ def image_to_base64(image: Image.Image) -> str:
53
+ if image is None:
54
+ return ""
55
+ if image.mode != "RGB":
56
+ image = image.convert("RGB")
57
+ buf = io.BytesIO()
58
+ image.save(buf, format="PNG")
59
+ return base64.b64encode(buf.getvalue()).decode()
60
+
61
+ def base64_to_image(b64: str) -> Optional[Image.Image]:
62
+ if not b64:
63
+ return None
64
+ try:
65
+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
66
+ except Exception as e:
67
+ logger.error(f"Failed to decode base64: {e}")
68
+ return None
69
+
70
+ def process_image(input_image: Image.Image):
71
+ """Process image through SAKS backend"""
72
+ if input_image is None:
73
+ return None
74
+
75
+ try:
76
+ if not backend_status["connected"]:
77
+ check_backend_connection()
78
+ if not backend_status["connected"]:
79
+ return None
80
+
81
+ client = backend_status["client"]
82
+ img_b64 = image_to_base64(input_image)
83
+
84
+ result = client.predict(
85
+ img_b64,
86
+ api_name="/predict",
87
+ )
88
+
89
+ if not result or len(result) < 1:
90
+ return None
91
+
92
+ output_b64 = result[0]
93
+ return base64_to_image(output_b64)
94
+
95
+ except Exception as e:
96
+ logger.error(f"Processing error: {e}")
97
+ return None
98
+
99
+ with gr.Blocks(title="SAKS") as demo:
100
+ gr.Markdown("# SAKS Jewelry Detection")
101
+
102
+ with gr.Row():
103
+ input_img = gr.Image(label="Input Image", type="pil")
104
+ output_img = gr.Image(label="Output Image")
105
+
106
+ process_btn = gr.Button("Process", variant="primary")
107
+
108
+ process_btn.click(
109
+ fn=process_image,
110
+ inputs=input_img,
111
+ outputs=output_img
112
+ )
113
+
114
+ if __name__ == "__main__":
115
+ demo.launch()