Nipun Claude commited on
Commit
0b80f1a
·
1 Parent(s): 3fee2ec

Switch to Docker-based deployment with proper FastAPI+Gradio integration

Browse files

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

Files changed (4) hide show
  1. Dockerfile +12 -0
  2. README.md +27 -18
  3. app.py +30 -47
  4. requirements.txt +1 -1
Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY app.py .
9
+
10
+ EXPOSE 7860
11
+
12
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,40 +1,49 @@
1
  ---
2
- title: Fastapi Gradio Demo
3
- emoji: 🚀
4
- colorFrom: blue
5
- colorTo: green
6
  sdk: docker
7
- sdk_version: 5.38.2
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- # FastAPI + Gradio Integration
13
 
14
- This app demonstrates how to combine FastAPI and Gradio for both API and web interface functionality.
15
 
16
- ## Features
 
 
 
17
 
18
- - **Gradio Web UI**: `/` (root) - Interactive web interface
19
- - **FastAPI endpoint**: `/api?a=<number>` - Returns JSON with `a` and `b=2*a`
20
- - **Health check**: `/health` - App status endpoint
21
 
22
- Both use the same core computation logic.
23
 
24
- ## Usage
 
 
 
25
 
26
- 1. **Web Interface**: Visit the root URL for the interactive Gradio UI
27
- 2. **API endpoint**: `GET /api?a=5` returns `{"a": 5, "b": 10}`
28
- 3. **Health check**: `GET /health` returns app status
29
 
30
  ## Local Development
31
 
32
  ```bash
33
  pip install -r requirements.txt
34
- python app.py
 
 
 
 
 
 
 
35
  ```
36
 
37
  The app will be available at:
38
  - UI: http://localhost:7860/
39
  - API: http://localhost:7860/api
40
- - Health: http://localhost:7860/health
 
1
  ---
2
+ title: Gradio + FastAPI App
3
+ emoji: 🔥
4
+ colorFrom: indigo
5
+ colorTo: cyan
6
  sdk: docker
 
7
  app_file: app.py
8
  pinned: false
9
  ---
10
 
11
+ # Gradio + FastAPI Hybrid App
12
 
13
+ This Hugging Face Space serves:
14
 
15
+ - ✅ Gradio UI at `/` (via `gr.Interface`)
16
+ - ✅ JSON API at `/api` (GET request with `?a=int`)
17
+ - ✅ CORS enabled
18
+ - ✅ OpenAPI docs at `/docs` (not visible in HF but works locally)
19
 
20
+ ## Example Usage
 
 
21
 
22
+ ### API
23
 
24
+ ```bash
25
+ curl "https://your-space.hf.space/api?a=10"
26
+ # Returns: {"a": 10, "b": 20}
27
+ ```
28
 
29
+ ### Web Interface
30
+
31
+ Visit the root URL for the interactive Gradio interface.
32
 
33
  ## Local Development
34
 
35
  ```bash
36
  pip install -r requirements.txt
37
+ uvicorn app:app --host 0.0.0.0 --port 7860
38
+ ```
39
+
40
+ Or with Docker:
41
+
42
+ ```bash
43
+ docker build -t gradio-fastapi .
44
+ docker run -p 7860:7860 gradio-fastapi
45
  ```
46
 
47
  The app will be available at:
48
  - UI: http://localhost:7860/
49
  - API: http://localhost:7860/api
 
app.py CHANGED
@@ -1,55 +1,38 @@
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  # Core logic
4
  def compute(a: int):
5
  return {"a": a, "b": 2 * a}
6
 
7
- # Gradio function for UI
8
- def gradio_compute(a):
9
- if a is None:
10
- return "Please enter a number"
11
- try:
12
- result = compute(int(a))
13
- return f"Result: a = {result['a']}, b = {result['b']}"
14
- except:
15
- return "Invalid input - please enter a valid number"
16
-
17
- # API function that returns JSON
18
- def api_compute(a):
19
- try:
20
- result = compute(int(a))
21
- return result
22
- except:
23
- return {"error": "Invalid input"}
24
-
25
- # Create Gradio interface
26
- with gr.Blocks(title="FastAPI + Gradio Calculator") as demo:
27
- gr.Markdown("# FastAPI + Gradio Calculator")
28
- gr.Markdown("Enter a number to compute a and b=2*a")
29
-
30
- with gr.Tab("Web Interface"):
31
- with gr.Row():
32
- input_num = gr.Number(label="Enter number 'a'", value=5)
33
- result_text = gr.Textbox(label="Result", interactive=False)
34
-
35
- submit_btn = gr.Button("Calculate")
36
- submit_btn.click(gradio_compute, inputs=input_num, outputs=result_text)
37
- input_num.submit(gradio_compute, inputs=input_num, outputs=result_text)
38
-
39
- gr.Examples([[5], [10], [42]], inputs=input_num)
40
-
41
- with gr.Tab("API"):
42
- gr.Markdown("## API Usage")
43
- gr.Markdown("Use the Gradio API endpoint:")
44
- gr.Markdown("```\nPOST /gradio_api/call/api_compute\n```")
45
-
46
- api_input = gr.Number(label="Enter number for API", value=5)
47
- api_output = gr.JSON(label="API Response")
48
- api_btn = gr.Button("Test API")
49
- api_btn.click(api_compute, inputs=api_input, outputs=api_output)
50
 
51
- # Make API function available
52
- demo.api_name = "api_compute"
 
 
 
 
 
 
53
 
54
- if __name__ == "__main__":
55
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ from fastapi import FastAPI, Query, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
  import gradio as gr
5
+ from gradio.routes import mount_gradio_app
6
+
7
+ # FastAPI app
8
+ app = FastAPI(title="Gradio + FastAPI Hybrid App", description="UI at `/`, API at `/api`", version="1.0")
9
+
10
+ # Enable CORS (for JS/frontend clients)
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"], # You can restrict this in prod
14
+ allow_credentials=True,
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
 
19
  # Core logic
20
  def compute(a: int):
21
  return {"a": a, "b": 2 * a}
22
 
23
+ # GET /api?a=10 JSON
24
+ @app.get("/api")
25
+ def get_api(a: int = Query(..., description="Input integer")):
26
+ return JSONResponse(content=compute(a))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Gradio UI app
29
+ gr_app = gr.Interface(
30
+ fn=compute,
31
+ inputs=gr.Number(label="Input a"),
32
+ outputs="json",
33
+ title="Double Calculator",
34
+ description="Returns JSON: {'a': a, 'b': 2a}"
35
+ )
36
 
37
+ # Mount Gradio UI at root `/`
38
+ app = mount_gradio_app(app, gr_app, path="/")
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
- gradio
2
  fastapi
 
3
  uvicorn
 
 
1
  fastapi
2
+ gradio
3
  uvicorn