-
Notifications
You must be signed in to change notification settings - Fork 883
feat: Standalone FastAPI web server adapter (env="fastapi") to bypass Jupyter dependencies
#741
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Sagar369r
wants to merge
2
commits into
Kanaries:main
Choose a base branch
from
Sagar369r:feat/fastapi-standalone-server-adapter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import sys | ||
| from pathlib import Path | ||
| import typer | ||
| import polars as pl | ||
|
|
||
| from .server import walk_server | ||
|
|
||
| app = typer.Typer(name="pygwalker-cli", help="PyGWalker Standalone Fast CLI - Zero Jupyter required.") | ||
|
|
||
|
|
||
| @app.command() | ||
| def main( | ||
| file_path: Path = typer.Argument(..., help="Path to CSV or Parquet dataset"), | ||
| port: int = typer.Option(8080, "--port", "-p", help="Port for the FastAPI server"), | ||
| no_browser: bool = typer.Option(False, "--no-browser", help="Do not automatically open the web browser"), | ||
| ): | ||
| """Start standalone Graphic-Walker web server for a dataset.""" | ||
| if not file_path.exists(): | ||
| typer.echo(f"Error: File '{file_path}' not found.", err=True) | ||
| raise typer.Exit(1) | ||
|
|
||
| typer.echo(f"Loading '{file_path}' into Polars Rust engine...") | ||
| if file_path.suffix.lower() == ".csv": | ||
| df = pl.read_csv(file_path, try_parse_dates=True, infer_schema_length=10000) | ||
| elif file_path.suffix.lower() == ".parquet": | ||
| df = pl.read_parquet(file_path) | ||
| else: | ||
| typer.echo("Unsupported file format. Please provide a CSV or Parquet file.", err=True) | ||
| raise typer.Exit(1) | ||
|
|
||
| typer.echo(f"Loaded dataset with shape {df.shape}. Starting server...") | ||
| walk_server(df, port=port, auto_open=not no_browser) | ||
|
|
||
|
|
||
| def entry_point(): | ||
| app() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| entry_point() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| import json | ||
| import webbrowser | ||
| import threading | ||
| import time | ||
| from typing import Union, List, Optional, Any, Dict | ||
|
|
||
| from fastapi import FastAPI, Request, Response | ||
| from fastapi.responses import HTMLResponse, JSONResponse | ||
| from fastapi.middleware.cors import CORSMiddleware | ||
| import uvicorn | ||
|
|
||
| from .pygwalker import PygWalker | ||
| from pygwalker.data_parsers.base import FieldSpec | ||
| from pygwalker._typing import DataFrame, IAppearance, IThemeKey | ||
| from pygwalker.utils.encode import DataFrameEncoder | ||
| from pygwalker.utils.free_port import find_free_port | ||
| from pygwalker.communications.base import BaseCommunication | ||
|
|
||
|
|
||
| def create_fastapi_server(walker: PygWalker) -> FastAPI: | ||
| """Create a high-performance FastAPI server to serve a PygWalker instance to the browser.""" | ||
| app = FastAPI(title="PyGWalker Fast Server (Jupyter Bypass)") | ||
|
|
||
| app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origins=["*"], | ||
| allow_credentials=True, | ||
| allow_methods=["*"], | ||
| allow_headers=["*"], | ||
| ) | ||
|
|
||
| # Initialize communication handler | ||
| walker.use_preview = False | ||
| walker._init_callback(BaseCommunication(str(walker.gid))) | ||
|
|
||
| @app.get("/", response_class=HTMLResponse) | ||
| async def get_index(): | ||
| props = walker._get_props("web_server") | ||
| props["communicationUrl"] = "/comm" | ||
| # Render HTML without jupyter iframe wrapping if desired, or with iframe | ||
| html = walker._get_render_iframe(props, return_iframe=False) | ||
| return HTMLResponse(content=html, status_code=200) | ||
|
|
||
| @app.post("/comm") | ||
|
Sagar369r marked this conversation as resolved.
|
||
| async def post_comm(request: Request): | ||
| payload = await request.json() | ||
| action = payload.get("action", "") | ||
| data = payload.get("data", {}) | ||
|
|
||
| # Handle message via communication handler | ||
| result = walker.comm._receive_msg(action, data) | ||
| encoded_json = json.dumps(result, cls=DataFrameEncoder) | ||
| return Response(content=encoded_json, media_type="application/json") | ||
|
|
||
| @app.get("/health") | ||
| async def health_check(): | ||
| return {"status": "ok", "gid": str(walker.gid)} | ||
|
|
||
| return app | ||
|
|
||
|
|
||
| def walk_server( | ||
| dataset: Union[DataFrame, Any], | ||
| gid: Optional[Union[int, str]] = None, | ||
| *, | ||
| field_specs: Optional[List[FieldSpec]] = None, | ||
| theme_key: IThemeKey = "g2", | ||
| appearance: IAppearance = "media", | ||
| spec: str = "", | ||
| spec_path: Optional[str] = None, | ||
| port: Optional[int] = None, | ||
| auto_open: bool = True, | ||
| **kwargs, | ||
| ) -> None: | ||
| """Launch PyGWalker as a standalone FastAPI web server directly in the browser (No Jupyter required).""" | ||
| if field_specs is None: | ||
| field_specs = [] | ||
|
|
||
| if port is None: | ||
| port = find_free_port() | ||
|
|
||
| walker = PygWalker( | ||
| gid=gid, | ||
| dataset=dataset, | ||
| field_specs=field_specs, | ||
| spec=spec, | ||
|
Sagar369r marked this conversation as resolved.
|
||
| source_invoke_code="", | ||
| theme_key=theme_key, | ||
| appearance=appearance, | ||
| show_cloud_tool=False, | ||
| use_preview=False, | ||
| kernel_computation=True, | ||
| use_save_tool=True, | ||
| gw_mode="explore", | ||
| is_export_dataframe=True, | ||
| kanaries_api_key="", | ||
| default_tab="vis", | ||
| cloud_computation=False, | ||
| **kwargs, | ||
| ) | ||
|
|
||
| app = create_fastapi_server(walker) | ||
| url = f"http://localhost:{port}" | ||
|
|
||
| def _open_browser(): | ||
| time.sleep(0.8) | ||
| try: | ||
| webbrowser.open(url) | ||
| except Exception: | ||
| pass | ||
|
|
||
| if auto_open: | ||
| threading.Thread(target=_open_browser, daemon=True).start() | ||
|
|
||
| print(f"\n🚀 PyGWalker Fast Server running at: {url}\nPress Ctrl+C to stop.\n") | ||
| uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.