scruffykay commited on
Commit
ce60d47
·
1 Parent(s): 916c1e0

alok nath ji

Browse files
Files changed (1) hide show
  1. app.py +22 -23
app.py CHANGED
@@ -1,13 +1,10 @@
1
- # app.py
2
-
3
  from fastapi import FastAPI, HTTPException
4
  from fastapi.exceptions import RequestValidationError
5
  from fastapi.responses import JSONResponse
6
- import gradio as gr
7
- import requests
8
- import os
9
- from contextlib import asynccontextmanager
10
 
 
11
  app = FastAPI()
12
 
13
  @app.exception_handler(RequestValidationError)
@@ -38,21 +35,26 @@ async def divide(a: float, b: float):
38
  if b == 0:
39
  raise HTTPException(status_code=400, detail="Cannot divide by zero")
40
  return {"result": a / b}
41
- # Gradio Interface
42
-
43
- # HUGGING FACE URL
44
- BACKEND_URL = "https://scruffykay2-100x-assignment-3.hf.space"
45
 
 
46
  def calculate(operation, num1, num2):
47
  try:
48
  num1, num2 = float(num1), float(num2)
49
- response = requests.get(f"{BACKEND_URL}/{operation}/{num1}/{num2}")
50
- if response.status_code == 200:
51
- return response.json()["result"]
 
 
 
 
 
52
  else:
53
- return f"Error: {response.json()['detail']}"
54
- except requests.RequestException:
55
- return "Error: Unable to connect to the backend"
 
 
 
56
 
57
  iface = gr.Interface(
58
  fn=calculate,
@@ -64,13 +66,10 @@ iface = gr.Interface(
64
  outputs="text"
65
  )
66
 
67
- @asynccontextmanager
68
- async def lifespan(app: FastAPI):
69
- iface.launch()
70
- yield
71
-
72
- app.router.lifespan_context = lifespan
73
 
 
74
  if __name__ == "__main__":
75
  import uvicorn
76
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ import gradio as gr
 
2
  from fastapi import FastAPI, HTTPException
3
  from fastapi.exceptions import RequestValidationError
4
  from fastapi.responses import JSONResponse
5
+ from fastapi.middleware.wsgi import WSGIMiddleware
 
 
 
6
 
7
+ # FastAPI setup
8
  app = FastAPI()
9
 
10
  @app.exception_handler(RequestValidationError)
 
35
  if b == 0:
36
  raise HTTPException(status_code=400, detail="Cannot divide by zero")
37
  return {"result": a / b}
 
 
 
 
38
 
39
+ # Gradio interface
40
  def calculate(operation, num1, num2):
41
  try:
42
  num1, num2 = float(num1), float(num2)
43
+ if operation == "add":
44
+ result = add(num1, num2)
45
+ elif operation == "subtract":
46
+ result = subtract(num1, num2)
47
+ elif operation == "multiply":
48
+ result = multiply(num1, num2)
49
+ elif operation == "divide":
50
+ result = divide(num1, num2)
51
  else:
52
+ return "Invalid operation"
53
+ return result["result"]
54
+ except HTTPException as e:
55
+ return f"Error: {e.detail}"
56
+ except Exception as e:
57
+ return f"Error: {str(e)}"
58
 
59
  iface = gr.Interface(
60
  fn=calculate,
 
66
  outputs="text"
67
  )
68
 
69
+ # Mount Gradio app to FastAPI
70
+ app = gr.mount_gradio_app(app, iface, path="/")
 
 
 
 
71
 
72
+ # For running locally
73
  if __name__ == "__main__":
74
  import uvicorn
75
+ uvicorn.run(app, host="0.0.0.0", port=7860)