NikhilSetiya commited on
Commit
6f446f3
·
1 Parent(s): 0e58639

Combine frontend and backend into single app.py

Browse files
Files changed (3) hide show
  1. app.py +89 -1
  2. backend.py +0 -46
  3. frontend.py +0 -50
app.py CHANGED
@@ -1,5 +1,93 @@
1
  import gradio as gr
2
- from frontend import demo
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  if __name__ == "__main__":
5
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
2
+ import requests
3
+ import os
4
+ from fastapi import FastAPI
5
+ from pydantic import BaseModel
6
+ from fastapi.middleware.cors import CORSMiddleware
7
 
8
+ # Create FastAPI app
9
+ app = FastAPI()
10
+
11
+ # Add CORS middleware
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ class CalculatorInput(BaseModel):
21
+ num1: float
22
+ num2: float
23
+ operation: str
24
+
25
+ class CalculatorResponse(BaseModel):
26
+ result: float
27
+ operation: str
28
+
29
+ @app.post("/calculate", response_model=CalculatorResponse)
30
+ async def calculate(input_data: CalculatorInput):
31
+ result = 0.0
32
+
33
+ if input_data.operation == "add":
34
+ result = input_data.num1 + input_data.num2
35
+ elif input_data.operation == "subtract":
36
+ result = input_data.num1 - input_data.num2
37
+ elif input_data.operation == "multiply":
38
+ result = input_data.num1 * input_data.num2
39
+ elif input_data.operation == "divide":
40
+ if input_data.num2 == 0:
41
+ raise ValueError("Cannot divide by zero")
42
+ result = input_data.num1 / input_data.num2
43
+ else:
44
+ raise ValueError("Invalid operation")
45
+
46
+ return CalculatorResponse(result=result, operation=input_data.operation)
47
+
48
+ # Create Gradio interface
49
+ def calculate_interface(num1: float, num2: float, operation: str) -> str:
50
+ try:
51
+ # Use the same URL as the frontend
52
+ backend_url = os.getenv("BACKEND_URL", "https://setiyanikhil3-calculator-app.hf.space")
53
+ response = requests.post(
54
+ f"{backend_url}/calculate",
55
+ json={
56
+ "num1": num1,
57
+ "num2": num2,
58
+ "operation": operation
59
+ }
60
+ )
61
+ response.raise_for_status()
62
+ result = response.json()
63
+ return f"Result: {result['result']}"
64
+ except requests.exceptions.RequestException as e:
65
+ return f"Error: {str(e)}"
66
+
67
+ # Create the Gradio interface
68
+ with gr.Blocks(title="Calculator") as demo:
69
+ gr.Markdown("# Calculator")
70
+ with gr.Row():
71
+ num1 = gr.Number(label="First Number")
72
+ num2 = gr.Number(label="Second Number")
73
+
74
+ with gr.Row():
75
+ operation = gr.Radio(
76
+ choices=["add", "subtract", "multiply", "divide"],
77
+ label="Operation",
78
+ value="add"
79
+ )
80
+
81
+ with gr.Row():
82
+ calculate_btn = gr.Button("Calculate")
83
+ result = gr.Textbox(label="Result")
84
+
85
+ calculate_btn.click(
86
+ fn=calculate_interface,
87
+ inputs=[num1, num2, operation],
88
+ outputs=result
89
+ )
90
+
91
+ # Launch the app
92
  if __name__ == "__main__":
93
  demo.launch(server_name="0.0.0.0", server_port=7860)
backend.py DELETED
@@ -1,46 +0,0 @@
1
- from fastapi import FastAPI
2
- from pydantic import BaseModel
3
- from fastapi.middleware.cors import CORSMiddleware
4
-
5
- app = FastAPI()
6
-
7
- # Add CORS middleware
8
- app.add_middleware(
9
- CORSMiddleware,
10
- allow_origins=["*"],
11
- allow_credentials=True,
12
- allow_methods=["*"],
13
- allow_headers=["*"],
14
- )
15
-
16
- class CalculatorInput(BaseModel):
17
- num1: float
18
- num2: float
19
- operation: str
20
-
21
- class CalculatorResponse(BaseModel):
22
- result: float
23
- operation: str
24
-
25
- @app.post("/calculate", response_model=CalculatorResponse)
26
- async def calculate(input_data: CalculatorInput):
27
- result = 0.0
28
-
29
- if input_data.operation == "add":
30
- result = input_data.num1 + input_data.num2
31
- elif input_data.operation == "subtract":
32
- result = input_data.num1 - input_data.num2
33
- elif input_data.operation == "multiply":
34
- result = input_data.num1 * input_data.num2
35
- elif input_data.operation == "divide":
36
- if input_data.num2 == 0:
37
- raise ValueError("Cannot divide by zero")
38
- result = input_data.num1 / input_data.num2
39
- else:
40
- raise ValueError("Invalid operation")
41
-
42
- return CalculatorResponse(result=result, operation=input_data.operation)
43
-
44
- if __name__ == "__main__":
45
- import uvicorn
46
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend.py DELETED
@@ -1,50 +0,0 @@
1
- import gradio as gr
2
- import requests
3
- import os
4
-
5
- # Get the backend URL from environment variable or use localhost as fallback
6
- BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:8000")
7
-
8
- def calculate(num1: float, num2: float, operation: str) -> str:
9
- try:
10
- response = requests.post(
11
- f"{BACKEND_URL}/calculate",
12
- json={
13
- "num1": num1,
14
- "num2": num2,
15
- "operation": operation
16
- }
17
- )
18
- response.raise_for_status()
19
- result = response.json()
20
- return f"Result: {result['result']}"
21
- except requests.exceptions.RequestException as e:
22
- return f"Error: {str(e)}"
23
-
24
- # Create the Gradio interface
25
- with gr.Blocks(title="Calculator") as demo:
26
- gr.Markdown("# Calculator")
27
- with gr.Row():
28
- num1 = gr.Number(label="First Number")
29
- num2 = gr.Number(label="Second Number")
30
-
31
- with gr.Row():
32
- operation = gr.Radio(
33
- choices=["add", "subtract", "multiply", "divide"],
34
- label="Operation",
35
- value="add"
36
- )
37
-
38
- with gr.Row():
39
- calculate_btn = gr.Button("Calculate")
40
- result = gr.Textbox(label="Result")
41
-
42
- calculate_btn.click(
43
- fn=calculate,
44
- inputs=[num1, num2, operation],
45
- outputs=result
46
- )
47
-
48
- # For Hugging Face Spaces
49
- if __name__ == "__main__":
50
- demo.launch(server_name="0.0.0.0", server_port=7860)