m7n commited on
Commit
aa8c944
·
verified ·
1 Parent(s): ee3b1c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -46
app.py CHANGED
@@ -1,86 +1,77 @@
1
  import os
2
- import re
3
  from pathlib import Path
4
  import json
5
  import base64
6
  from datetime import datetime
7
 
 
8
  import gradio as gr
9
- from fastapi import FastAPI, Request, Response
10
  from fastapi.staticfiles import StaticFiles
11
  import uvicorn
12
- import httpx
13
 
 
14
  import spaces
15
  from spaces.zero.client import _get_token
16
 
17
- # Set environment variables so Gradio builds its URLs.
18
- os.environ["GRADIO_SSR_MODE"] = "True"
19
- os.environ["GRADIO_SERVER_PORT"] = "7860"
20
- os.environ["GRADIO_SERVER_NAME"] = "0.0.0.0"
21
- # Tell Gradio what the node server is (host and port)
22
- os.environ["GRADIO_NODE_SERVER_NAME"] = "127.0.0.1:7861"
23
- os.environ["GRADIO_ROOT_PATH"] = "/"
24
-
25
  # Create FastAPI app
26
  app = FastAPI()
27
 
28
- # (Optional) Mount static files
29
  static_dir = Path("./static")
30
  static_dir.mkdir(parents=True, exist_ok=True)
 
 
31
  app.mount("/static", StaticFiles(directory="static"), name="static")
32
- os.environ["GRADIO_ALLOWED_PATHS"] = str(static_dir.resolve())
33
 
34
- # RESPONSE MIDDLEWARE TO FIX SSR ASSET URLS
35
- @app.middleware("http")
36
- async def fix_asset_urls(request: Request, call_next):
37
- response = await call_next(request)
38
- content_type = response.headers.get("content-type", "")
39
- # Process only HTML responses
40
- if "text/html" in content_type:
41
- # Read the entire response body
42
- body = b""
43
- async for chunk in response.body_iterator:
44
- body += chunk
45
- # Step 1: Insert a slash after ':7861' if not already present.
46
- fixed_body = re.sub(rb'(:7861)(?!/)', rb'\1/', body)
47
- # Step 2: Fix the _appimmutable segment:
48
- # Replace "_appimmutable" with "_app/immutable"
49
- fixed_body = re.sub(rb'(_app)(immutable)', rb'\1/immutable', fixed_body)
50
- # Step 3: Ensure that after "_app/immutable" there is a slash.
51
- fixed_body = re.sub(rb'(_app/immutable)(?!/)', rb'\1/', fixed_body)
52
- # Step 4: If "assets" is immediately followed by an uppercase letter, insert a slash.
53
- fixed_body = re.sub(rb'(assets)(?=[A-Z])', rb'\1/', fixed_body)
54
- # Build a new HTML response using the fixed body.
55
- response = Response(content=fixed_body,
56
- status_code=response.status_code,
57
- headers=dict(response.headers),
58
- media_type="text/html")
59
- return response
60
 
61
- @spaces.GPU(duration=4*60)
62
  def process_text(text):
 
63
  return text.upper()
64
 
65
  def process_and_save(request: gr.Request, text):
 
 
66
  token = _get_token(request)
67
  payload = token.split('.')[1]
68
  payload = f"{payload}{'=' * ((4 - len(payload) % 4) % 4)}"
69
  payload = json.loads(base64.urlsafe_b64decode(payload).decode())
70
- print(f"Token payload: {payload}")
 
 
71
  processed_text = process_text(text)
72
- return processed_text
 
 
 
 
 
 
 
73
 
 
74
  process_and_save.zerogpu = True
75
 
 
76
  with gr.Blocks() as demo:
77
  text_input = gr.Textbox(label="Enter some text")
78
  submit_btn = gr.Button("Process and Download")
79
- output = gr.Textbox(label="Output")
80
- submit_btn.click(fn=process_and_save, inputs=[text_input], outputs=output)
 
 
 
 
 
81
 
82
- # Mount the Gradio app into FastAPI using SSR mode (node_port 7861).
83
- app = gr.mount_gradio_app(app, demo, path="/", ssr_mode=True, node_port=7861)
84
 
 
85
  if __name__ == "__main__":
 
 
86
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  import os
 
2
  from pathlib import Path
3
  import json
4
  import base64
5
  from datetime import datetime
6
 
7
+ # Standard imports
8
  import gradio as gr
9
+ from fastapi import FastAPI, Request
10
  from fastapi.staticfiles import StaticFiles
11
  import uvicorn
 
12
 
13
+ # Hugging Face Spaces imports
14
  import spaces
15
  from spaces.zero.client import _get_token
16
 
 
 
 
 
 
 
 
 
17
  # Create FastAPI app
18
  app = FastAPI()
19
 
20
+ # Create and configure static directory
21
  static_dir = Path("./static")
22
  static_dir.mkdir(parents=True, exist_ok=True)
23
+
24
+ # Mount static directory to FastAPI
25
  app.mount("/static", StaticFiles(directory="static"), name="static")
 
26
 
27
+ # Tell Gradio which paths are allowed to be served
28
+ os.environ["GRADIO_ALLOWED_PATHS"] = str(static_dir.resolve())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ @spaces.GPU(duration=60) # Specify GPU duration in seconds
31
  def process_text(text):
32
+ """Example GPU function - in reality, this might be model inference"""
33
  return text.upper()
34
 
35
  def process_and_save(request: gr.Request, text):
36
+ """Main processing function that handles tokens and calls GPU function"""
37
+ # Get and decode the authentication token
38
  token = _get_token(request)
39
  payload = token.split('.')[1]
40
  payload = f"{payload}{'=' * ((4 - len(payload) % 4) % 4)}"
41
  payload = json.loads(base64.urlsafe_b64decode(payload).decode())
42
+ print(f"Token payload: {payload}") # For debugging
43
+
44
+ # Process the text using GPU function
45
  processed_text = process_text(text)
46
+
47
+ # Save to file
48
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
49
+ file_path = static_dir / f"output_{timestamp}.txt"
50
+ with open(file_path, "w") as f:
51
+ f.write(processed_text)
52
+
53
+ return gr.File(value=file_path)
54
 
55
+ # Mark main function as not requiring GPU
56
  process_and_save.zerogpu = True
57
 
58
+ # Create Gradio interface
59
  with gr.Blocks() as demo:
60
  text_input = gr.Textbox(label="Enter some text")
61
  submit_btn = gr.Button("Process and Download")
62
+ output = gr.File(label="Download Processed File")
63
+
64
+ submit_btn.click(
65
+ fn=process_and_save,
66
+ inputs=[text_input],
67
+ outputs=output
68
+ )
69
 
70
+ # Mount Gradio app to FastAPI with SSR mode for Spaces
71
+ app = gr.mount_gradio_app(app, demo, path="/", ssr_mode=True)
72
 
73
+ # Run server
74
  if __name__ == "__main__":
75
+ # Set SSR mode for Spaces
76
+ os.environ["GRADIO_SSR_MODE"] = "True"
77
  uvicorn.run(app, host="0.0.0.0", port=7860)