videopix commited on
Commit
014acf3
·
verified ·
1 Parent(s): eb023cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -31
app.py CHANGED
@@ -23,18 +23,16 @@ model_lock = asyncio.Lock()
23
  # Token Authentication
24
  # ---------------------------------------------------
25
 
26
- API_TOKEN = os.getenv("img2caption") # your secret token from variables
27
 
28
- async def verify_token(authorization: str = Header(None)):
29
- if authorization is None or not authorization.startswith("Bearer "):
30
  raise HTTPException(status_code=401, detail="Missing Authorization header")
31
 
32
- token = authorization.split("Bearer ")[-1].strip()
33
-
34
  if token != API_TOKEN:
35
  raise HTTPException(status_code=403, detail="Invalid token")
36
 
37
-
38
  # ---------------------------------------------------
39
  # Lazy Florence Model Load
40
  # ---------------------------------------------------
@@ -78,33 +76,41 @@ def run_caption(image: Image.Image) -> str:
78
 
79
 
80
  # ---------------------------------------------------
81
- # API Endpoint
82
  # ---------------------------------------------------
83
- @app.post("/img2caption")
84
- async def img2caption(
85
- file: UploadFile = File(...),
86
- _: None = Depends(verify_token)
87
- ):
88
- try:
89
- async with model_lock:
90
- await load_model()
91
-
92
- data = await file.read()
93
- image = Image.open(io.BytesIO(data)).convert("RGB")
94
 
95
- caption = run_caption(image)
 
 
 
96
 
97
- return {"caption": caption}
 
 
 
98
 
99
- except Exception as e:
100
- return JSONResponse({"error": str(e)}, status_code=500)
 
101
 
102
 
103
  # ---------------------------------------------------
104
- # Protected HTML UI
105
  # ---------------------------------------------------
106
- @app.get("/", response_class=HTMLResponse)
107
- async def ui(_: None = Depends(verify_token)):
 
 
108
  return """
109
  <!DOCTYPE html>
110
  <html>
@@ -136,8 +142,8 @@ async def ui(_: None = Depends(verify_token)):
136
  let token = sessionStorage.getItem("authToken");
137
 
138
  if (!token) {
139
- token = prompt("Enter access token:");
140
- sessionStorage.setItem("authToken", token);
141
  }
142
 
143
  const imageInput = document.getElementById("imageInput");
@@ -163,7 +169,7 @@ async def ui(_: None = Depends(verify_token)):
163
  form.append("file", f);
164
 
165
  captionBox.style.display = "block";
166
- captionBox.innerHTML = "Generating caption...";
167
 
168
  const res = await fetch("/img2caption", {
169
  method: "POST",
@@ -172,7 +178,7 @@ async def ui(_: None = Depends(verify_token)):
172
  });
173
 
174
  const data = await res.json();
175
- captionBox.innerHTML = data.caption || data.error;
176
  }
177
  </script>
178
 
@@ -182,13 +188,34 @@ async def ui(_: None = Depends(verify_token)):
182
 
183
 
184
  # ---------------------------------------------------
185
- # Run locally
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  # ---------------------------------------------------
187
  def keep_alive():
188
  pass
189
 
190
  if __name__ == "__main__":
191
  import uvicorn
192
- print("🚀 Launching Fast img2caption API")
193
  keep_alive()
194
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
23
  # Token Authentication
24
  # ---------------------------------------------------
25
 
26
+ API_TOKEN = os.getenv("img2caption") # secret token from your environment
27
 
28
+ def check_token(auth: str):
29
+ if auth is None or not auth.startswith("Bearer "):
30
  raise HTTPException(status_code=401, detail="Missing Authorization header")
31
 
32
+ token = auth.split("Bearer ")[-1].strip()
 
33
  if token != API_TOKEN:
34
  raise HTTPException(status_code=403, detail="Invalid token")
35
 
 
36
  # ---------------------------------------------------
37
  # Lazy Florence Model Load
38
  # ---------------------------------------------------
 
76
 
77
 
78
  # ---------------------------------------------------
79
+ # Public Login Page
80
  # ---------------------------------------------------
81
+ @app.get("/", response_class=HTMLResponse)
82
+ def login_page():
83
+ return """
84
+ <!DOCTYPE html>
85
+ <html>
86
+ <head><title>Login</title></head>
87
+ <body style="font-family:Arial;max-width:500px;margin:40px auto;">
88
+ <h2>Access Token Required</h2>
89
+ <input id="token" type="password" style="width:100%;padding:10px;" placeholder="Enter token">
90
+ <button onclick="login()" style="padding:10px;margin-top:10px;width:100%;">Continue</button>
 
91
 
92
+ <script>
93
+ function login() {
94
+ const t = document.getElementById("token").value;
95
+ if (!t) return alert("Token required");
96
 
97
+ sessionStorage.setItem("authToken", t);
98
+ window.location.href = "/ui";
99
+ }
100
+ </script>
101
 
102
+ </body>
103
+ </html>
104
+ """
105
 
106
 
107
  # ---------------------------------------------------
108
+ # Protected UI
109
  # ---------------------------------------------------
110
+ @app.get("/ui", response_class=HTMLResponse)
111
+ async def ui_page(authorization: str = Header(None)):
112
+ check_token(authorization)
113
+
114
  return """
115
  <!DOCTYPE html>
116
  <html>
 
142
  let token = sessionStorage.getItem("authToken");
143
 
144
  if (!token) {
145
+ alert("No token found, please login again.");
146
+ window.location.href = "/";
147
  }
148
 
149
  const imageInput = document.getElementById("imageInput");
 
169
  form.append("file", f);
170
 
171
  captionBox.style.display = "block";
172
+ captionBox.textContent = "Generating caption...";
173
 
174
  const res = await fetch("/img2caption", {
175
  method: "POST",
 
178
  });
179
 
180
  const data = await res.json();
181
+ captionBox.textContent = data.caption || data.error;
182
  }
183
  </script>
184
 
 
188
 
189
 
190
  # ---------------------------------------------------
191
+ # Protected Caption API
192
+ # ---------------------------------------------------
193
+ @app.post("/img2caption")
194
+ async def img2caption(file: UploadFile = File(...), authorization: str = Header(None)):
195
+ check_token(authorization)
196
+
197
+ try:
198
+ async with model_lock:
199
+ await load_model()
200
+
201
+ data = await file.read()
202
+ image = Image.open(io.BytesIO(data)).convert("RGB")
203
+ caption = run_caption(image)
204
+
205
+ return {"caption": caption}
206
+
207
+ except Exception as e:
208
+ return JSONResponse({"error": str(e)}, status_code=500)
209
+
210
+
211
+ # ---------------------------------------------------
212
+ # Local Run
213
  # ---------------------------------------------------
214
  def keep_alive():
215
  pass
216
 
217
  if __name__ == "__main__":
218
  import uvicorn
219
+ print("🚀 Launching img2caption API")
220
  keep_alive()
221
  uvicorn.run(app, host="0.0.0.0", port=7860)