qqwjq1981 commited on
Commit
684a830
·
verified ·
1 Parent(s): 31ab1b5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -44
app.py CHANGED
@@ -791,19 +791,21 @@ def fetch_updated_state():
791
  logger.debug(f"{key}: String: {value}")
792
  else:
793
  logger.debug(f"{key}: Unsupported type: {value}")
794
- response = requests.get("http://localhost:5000/state")
795
- # Check the status code and the raw response
796
- if response.status_code == 200:
797
- try:
798
- state = response.json() # Try to parse JSON
799
- return pd.DataFrame(state["project_desc_table"]), state["task_analysis_txt"], pd.DataFrame(state["execution_status"]), state["execution_results"]
800
- except ValueError as e:
801
- logger.error(f"JSON decoding failed: {e}")
802
- logger.debug("Raw response body:", response.text)
803
- else:
804
- logger.error(f"Error: {response.status_code} - {response.text}")
805
- """Fetch the updated shared state from FastAPI."""
806
- return pd.DataFrame(), "", pd.DataFrame(), {}
 
 
807
 
808
 
809
  def update_gradio_state(project_desc_table, task_analysis_txt, execution_status, execution_results):
@@ -1161,39 +1163,72 @@ def create_gradio_interface(state=None):
1161
  # Load function to initialize the state
1162
  # demo.load(load_fn, inputs=None, outputs=[state]) # Initialize the state when the page is loaded
1163
 
1164
- # In[21]:
1165
- demo = create_gradio_interface()
1166
- # Use Gradio's `server_app` to get an ASGI app for Blocks
1167
- gradio_asgi_app = demo.launch(share=False, inbrowser=False, server_name="0.0.0.0", server_port=7860, inline=False)
1168
-
1169
- logging.debug(f"Gradio version: {gr.__version__}")
1170
- logging.debug(f"FastAPI version: {fastapi.__version__}")
1171
-
1172
- # Mount the Gradio ASGI app at "/gradio"
1173
- app.mount("/gradio", gradio_asgi_app)
1174
-
1175
- # create a static directory to store the static files
1176
- static_dir = Path('./static')
1177
- static_dir.mkdir(parents=True, exist_ok=True)
1178
 
1179
- # mount FastAPI StaticFiles server
1180
- app.mount("/static", StaticFiles(directory=static_dir), name="static")
 
 
 
1181
 
1182
- # Dynamically check for the Gradio asset directory
1183
- # gradio_assets_path = os.path.join(os.path.dirname(gr.__file__), "static")
1184
-
1185
- # if os.path.exists(gradio_assets_path):
1186
- # # If assets exist, mount them
1187
- # app.mount("/assets", StaticFiles(directory=gradio_assets_path), name="assets")
1188
- # else:
1189
- # logging.error(f"Gradio assets directory not found at: {gradio_assets_path}")
1190
-
1191
- # Redirect from the root endpoint to the Gradio app
1192
- @app.get("/", response_class=RedirectResponse)
1193
  async def index():
1194
- return RedirectResponse(url="/gradio", status_code=307)
 
 
 
 
 
 
 
 
 
 
 
1195
 
1196
- # Run the FastAPI server using uvicorn
1197
  if __name__ == "__main__":
1198
- # port = int(os.getenv("PORT", 5000)) # Default to 7860 if PORT is not set
1199
- uvicorn.run(app, host="0.0.0.0", port=5000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791
  logger.debug(f"{key}: String: {value}")
792
  else:
793
  logger.debug(f"{key}: Unsupported type: {value}")
794
+ return shared_state['project_desc_table'], shared_state['task_analysis_txt'], shared_state['execution_status'], shared_state['execution_results']
795
+
796
+ # response = requests.get("http://localhost:5000/state")
797
+ # # Check the status code and the raw response
798
+ # if response.status_code == 200:
799
+ # try:
800
+ # state = response.json() # Try to parse JSON
801
+ # return pd.DataFrame(state["project_desc_table"]), state["task_analysis_txt"], pd.DataFrame(state["execution_status"]), state["execution_results"]
802
+ # except ValueError as e:
803
+ # logger.error(f"JSON decoding failed: {e}")
804
+ # logger.debug("Raw response body:", response.text)
805
+ # else:
806
+ # logger.error(f"Error: {response.status_code} - {response.text}")
807
+ # """Fetch the updated shared state from FastAPI."""
808
+ # return pd.DataFrame(), "", pd.DataFrame(), {}
809
 
810
 
811
  def update_gradio_state(project_desc_table, task_analysis_txt, execution_status, execution_results):
 
1163
  # Load function to initialize the state
1164
  # demo.load(load_fn, inputs=None, outputs=[state]) # Initialize the state when the page is loaded
1165
 
1166
+ # Function to launch Gradio
1167
+ def launch_gradio():
1168
+ demo = create_gradio_interface()
1169
+ demo.launch(share=True, inline=False) # Gradio in the foreground
 
 
 
 
 
 
 
 
 
 
1170
 
1171
+ # Function to run FastAPI server using uvicorn in the background
1172
+ async def run_fastapi():
1173
+ config = uvicorn.Config(app, host="0.0.0.0", port=5000, reload=True, log_level="debug")
1174
+ server = uvicorn.Server(config)
1175
+ await server.serve()
1176
 
1177
+ # FastAPI endpoint to display a message
1178
+ @app.get("/", response_class=HTMLResponse)
 
 
 
 
 
 
 
 
 
1179
  async def index():
1180
+ return "FastAPI is running. Visit Gradio at the provided public URL."
1181
+
1182
+ # Main entry point for the asynchronous execution
1183
+ async def main():
1184
+ # Run Gradio in the foreground and FastAPI in the background
1185
+ loop = asyncio.get_event_loop()
1186
+
1187
+ # Run Gradio in a separate thread (non-blocking)
1188
+ loop.run_in_executor(None, launch_gradio)
1189
+
1190
+ # Run FastAPI in the background (asynchronous)
1191
+ await run_fastapi()
1192
 
 
1193
  if __name__ == "__main__":
1194
+ import nest_asyncio
1195
+ nest_asyncio.apply() # Allow nested use of asyncio event loops in Jupyter notebooks
1196
+
1197
+ # Run the main function to launch both services concurrently
1198
+ asyncio.run(main())
1199
+ # # In[21]:
1200
+ # demo = create_gradio_interface()
1201
+ # # Use Gradio's `server_app` to get an ASGI app for Blocks
1202
+ # gradio_asgi_app = demo.launch(share=False, inbrowser=False, server_name="0.0.0.0", server_port=7860, inline=False)
1203
+
1204
+ # logging.debug(f"Gradio version: {gr.__version__}")
1205
+ # logging.debug(f"FastAPI version: {fastapi.__version__}")
1206
+
1207
+ # # Mount the Gradio ASGI app at "/gradio"
1208
+ # app.mount("/gradio", gradio_asgi_app)
1209
+
1210
+ # # create a static directory to store the static files
1211
+ # static_dir = Path('./static')
1212
+ # static_dir.mkdir(parents=True, exist_ok=True)
1213
+
1214
+ # # mount FastAPI StaticFiles server
1215
+ # app.mount("/static", StaticFiles(directory=static_dir), name="static")
1216
+
1217
+ # # Dynamically check for the Gradio asset directory
1218
+ # # gradio_assets_path = os.path.join(os.path.dirname(gr.__file__), "static")
1219
+
1220
+ # # if os.path.exists(gradio_assets_path):
1221
+ # # # If assets exist, mount them
1222
+ # # app.mount("/assets", StaticFiles(directory=gradio_assets_path), name="assets")
1223
+ # # else:
1224
+ # # logging.error(f"Gradio assets directory not found at: {gradio_assets_path}")
1225
+
1226
+ # # Redirect from the root endpoint to the Gradio app
1227
+ # @app.get("/", response_class=RedirectResponse)
1228
+ # async def index():
1229
+ # return RedirectResponse(url="/gradio", status_code=307)
1230
+
1231
+ # # Run the FastAPI server using uvicorn
1232
+ # if __name__ == "__main__":
1233
+ # # port = int(os.getenv("PORT", 5000)) # Default to 7860 if PORT is not set
1234
+ # uvicorn.run(app, host="0.0.0.0", port=5000)