Skip to content

feat: Add --gradio-ui option to launch.py#90

Merged
MasumRab merged 1 commit intomainfrom
feature/gradio-ui-launch
Jun 17, 2025
Merged

feat: Add --gradio-ui option to launch.py#90
MasumRab merged 1 commit intomainfrom
feature/gradio-ui-launch

Conversation

@MasumRab
Copy link
Copy Markdown
Owner

@MasumRab MasumRab commented Jun 17, 2025

This commit introduces a new --gradio-ui command-line option to the main launch.py script. This option allows you to directly launch the Gradio-based scientific UI (server/python_backend/gradio_app.py) for testing, AI model interaction, and UI component exploration.

Changes include:

  • Added --gradio-ui argument to launch.py.
  • Implemented logic in run_application within launch.py to execute gradio_app.py when --gradio-ui is specified.
  • Modified server/python_backend/gradio_app.py to accept --host, --port, --debug, and --share command-line arguments, allowing its server parameters to be controlled by launch.py.
  • Updated README.md to document the new --gradio-ui feature and its usage.

This addresses the issue where the local non-Docker Python-only scientific deployment using Gradio had "disappeared" by providing a clear, integrated way to launch it.

Summary by Sourcery

Add a new --gradio-ui mode to the launcher that starts the standalone Gradio-based scientific UI with configurable server options and document its usage in the README

New Features:

  • Introduce --gradio-ui flag to launch.py for directly starting the Gradio scientific UI

Enhancements:

  • Extend gradio_app.py to accept host, port, debug, and share arguments
  • Implement subprocess orchestration and environment setup in launch.py for running the Gradio UI

Documentation:

  • Add documentation in README.md for using the --gradio-ui option and configuring its parameters

Summary by CodeRabbit

  • New Features

    • Introduced a Gradio-based scientific UI that can be launched independently for AI model interaction or UI testing.
    • Added a new launcher flag to start the Gradio UI with customizable host, port, debug, and sharing options.
  • Documentation

    • Updated the README with detailed instructions on running the Gradio Scientific UI, including platform-specific commands and configuration guidance.

This commit introduces a new `--gradio-ui` command-line option to the main `launch.py` script. This option allows you to directly launch the Gradio-based scientific UI (`server/python_backend/gradio_app.py`) for testing, AI model interaction, and UI component exploration.

Changes include:
- Added `--gradio-ui` argument to `launch.py`.
- Implemented logic in `run_application` within `launch.py` to execute `gradio_app.py` when `--gradio-ui` is specified.
- Modified `server/python_backend/gradio_app.py` to accept `--host`, `--port`, `--debug`, and `--share` command-line arguments, allowing its server parameters to be controlled by `launch.py`.
- Updated `README.md` to document the new `--gradio-ui` feature and its usage.

This addresses the issue where the local non-Docker Python-only scientific deployment using Gradio had "disappeared" by providing a clear, integrated way to launch it.
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Jun 17, 2025

Reviewer's Guide

This PR adds a new --gradio-ui flag to the main launch.py script, wiring it into run_application to spawn the Gradio UI as a subprocess with configurable host, port, debug, and share options; extends gradio_app.py to parse and apply those CLI parameters; and updates the README to document the workflow.

Sequence diagram for launching Gradio UI via --gradio-ui flag

sequenceDiagram
    actor User
    participant LaunchPy as launch.py
    participant GradioApp as gradio_app.py

    User->>LaunchPy: Run with --gradio-ui [and options]
    LaunchPy->>LaunchPy: Parse arguments
    LaunchPy->>LaunchPy: Detect --gradio-ui flag
    LaunchPy->>GradioApp: Spawn subprocess with --host, --port, --debug, --share
    GradioApp->>GradioApp: Parse CLI arguments
    GradioApp->>GradioApp: Launch Gradio UI with specified options
    GradioApp-->>User: Gradio UI available at host:port
    Note over GradioApp,User: If --share, Gradio provides .gradio.live URL
    User->>LaunchPy: Ctrl+C to stop
    LaunchPy->>GradioApp: Terminate subprocess
    GradioApp-->>LaunchPy: Exit
    LaunchPy-->>User: Exit
Loading

Class diagram for argument parsing and Gradio UI launch

classDiagram
    class LaunchArguments {
        +bool gradio_ui
        +str host
        +int port
        +bool debug
        +bool share
    }
    class LaunchPy {
        +run_application(args)
        +parse_arguments()
    }
    class GradioApp {
        +main()
        +parse_args()
        +iface.launch(server_name, server_port, debug, share)
    }
    LaunchPy --|> LaunchArguments : uses
    LaunchPy ..> GradioApp : spawns subprocess with args
    GradioApp --|> LaunchArguments : parses
Loading

File-Level Changes

Change Details Files
Introduce the --gradio-ui flag and subprocess launch logic in launch.py
  • Added --gradio-ui argument in the CLI parser
  • Branched run_application to detect args.gradio_ui before api_only
  • Constructed a command array including --host, --port, --debug, and --share
  • Set PYTHONPATH in the subprocess environment and launched gradio_app.py
  • Logged startup info, handled process waiting, return codes, and errors
launch.py
Extend gradio_app.py to accept and apply server parameters
  • Added argparse for --host, --port, --debug, and --share
  • Built launch_kwargs dict to pass to iface.launch()
  • Conditionally included server_port only when provided
  • Printed chosen launch options before starting the interface
server/python_backend/gradio_app.py
Document the new Gradio UI workflow in README.md
  • Added a “Running the Gradio Scientific UI” section
  • Provided example commands for Linux/macOS and Windows
  • Outlined how to customize host, port, debug, and share options
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 17, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

A new launcher flag (--gradio-ui) and supporting logic were added to enable running the Gradio-based scientific UI independently from the main application. The Gradio app script now accepts command-line arguments for host, port, debug, and sharing options, allowing flexible runtime configuration. Documentation was updated with usage instructions.

Changes

File(s) Change Summary
README.md Added documentation for running the Gradio Scientific UI, including usage instructions and options.
launch.py Added --gradio-ui flag, subprocess logic to launch Gradio UI with configurable options, and error handling.
server/python_backend/gradio_app.py Enhanced to accept command-line arguments for host, port, debug, and share; launches Gradio with these.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Launcher (launch.py)
    participant Gradio Script (gradio_app.py)
    participant Gradio UI

    User->>Launcher (launch.py): Run with --gradio-ui [and options]
    Launcher (launch.py)->>Gradio Script (gradio_app.py): Start subprocess with CLI args
    Gradio Script (gradio_app.py)->>Gradio UI: Launch with specified host/port/debug/share
    Gradio UI-->>User: Exposes web interface at configured URL
Loading

Possibly related PRs

Poem

A rabbit hops with code anew,
Now Gradio shines with options true!
Just add a flag, and off you go,
Host and port—set to flow.
With science and testing at your side,
The UI leaps—enjoy the ride!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5246bd1 and 927c83b.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • launch.py (2 hunks)
  • server/python_backend/gradio_app.py (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MasumRab MasumRab merged commit 0ab4f60 into main Jun 17, 2025
2 of 3 checks passed
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @MasumRab - I've reviewed your changes - here's some feedback:

Blocking issues:

  • Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'. (link)

General comments:

  • Extract the Gradio launch logic into a separate helper (e.g. launch_gradio_ui) instead of inlining it inside run_application to improve readability and maintainability.
  • Introduce dedicated CLI flags for Gradio UI (e.g. --gradio-host/--gradio-port) rather than reusing --host/--port to avoid collisions with the main backend settings.
  • Use subprocess.run for synchronous execution to simplify exit‐code handling and double‐check that the global processes list is properly initialized and scoped.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Extract the Gradio launch logic into a separate helper (e.g. launch_gradio_ui) instead of inlining it inside run_application to improve readability and maintainability.
- Introduce dedicated CLI flags for Gradio UI (e.g. --gradio-host/--gradio-port) rather than reusing --host/--port to avoid collisions with the main backend settings.
- Use subprocess.run for synchronous execution to simplify exit‐code handling and double‐check that the global `processes` list is properly initialized and scoped.

## Individual Comments

### Comment 1
<location> `launch.py:841` </location>
<code_context>
+        # so passing args.host to gradio_app.py correctly handles this.
+
+        env = os.environ.copy()
+        env["PYTHONPATH"] = str(ROOT_DIR)
+        # Add any other necessary environment variables if gradio_app.py needs them.
+        # For example, if Gradio needs to know the API URL for some features:
</code_context>

<issue_to_address>
Overwriting PYTHONPATH may unintentionally remove existing entries.

Prepend or append ROOT_DIR to the existing PYTHONPATH to avoid breaking setups that rely on its current value.
</issue_to_address>

### Comment 2
<location> `launch.py:822` </location>
<code_context>
             logger.warning(f"Specified env file {args.env_file} not found at {env_file_path}")

-    if args.api_only:
+    if args.gradio_ui:
+        logger.info("Running Gradio UI for scientific/testing purposes...")
+        gradio_script_path = ROOT_DIR / "server" / "python_backend" / "gradio_app.py"
</code_context>

<issue_to_address>
Consider extracting the Gradio UI launch logic into a separate helper function to keep run_application() concise.

```suggestion
# Extract the Gradio‐UI block into its own helper to keep run_application() shallow
# e.g. somewhere near start_backend()/start_frontend():
def start_gradio_ui(args, python_executable):
    gradio_script = ROOT_DIR / "server" / "python_backend" / "gradio_app.py"
    if not gradio_script.exists():
        logger.error(f"Gradio script not found at: {gradio_script}")
        return 1

    cmd = [
        python_executable,
        str(gradio_script),
        "--host", args.host,
        "--port", str(args.port),
    ]
    if args.share:
        cmd.append("--share")
    if args.debug:
        cmd.append("--debug")

    env = os.environ.copy()
    env["PYTHONPATH"] = str(ROOT_DIR)
    # add more env vars here if needed, e.g. API_URL

    try:
        logger.info(f"Running Gradio UI command: {' '.join(cmd)}")
        proc = subprocess.Popen(cmd, env=env)
        logger.info(f"Gradio UI started (PID {proc.pid}). Access at http://{args.host or '127.0.0.1'}:{args.port}")
        proc.wait()
        if proc.returncode != 0:
            logger.warning(f"Gradio exited with code {proc.returncode}")
        return 0
    except FileNotFoundError:
        logger.error("Python executable or Gradio not found. Install gradio in your env.")
        return 1
    except Exception as e:
        logger.error(f"Failed to start Gradio UI: {e}")
        return 1

# Then simplify run_application():
...
    if args.gradio_ui:
        return start_gradio_ui(args, python_executable)
    elif args.api_only:
        ...
```
</issue_to_address>

## Security Issues

### Issue 1
<location> `launch.py:848` </location>

<issue_to_address>
**security (dangerous-subprocess-use-audit):** Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

# so passing args.host to gradio_app.py correctly handles this.

env = os.environ.copy()
env["PYTHONPATH"] = str(ROOT_DIR)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Overwriting PYTHONPATH may unintentionally remove existing entries.

Prepend or append ROOT_DIR to the existing PYTHONPATH to avoid breaking setups that rely on its current value.

logger.warning(f"Specified env file {args.env_file} not found at {env_file_path}")

if args.api_only:
if args.gradio_ui:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider extracting the Gradio UI launch logic into a separate helper function to keep run_application() concise.

Suggested change
if args.gradio_ui:
# Extract the Gradio‐UI block into its own helper to keep run_application() shallow
# e.g. somewhere near start_backend()/start_frontend():
def start_gradio_ui(args, python_executable):
gradio_script = ROOT_DIR / "server" / "python_backend" / "gradio_app.py"
if not gradio_script.exists():
logger.error(f"Gradio script not found at: {gradio_script}")
return 1
cmd = [
python_executable,
str(gradio_script),
"--host", args.host,
"--port", str(args.port),
]
if args.share:
cmd.append("--share")
if args.debug:
cmd.append("--debug")
env = os.environ.copy()
env["PYTHONPATH"] = str(ROOT_DIR)
# add more env vars here if needed, e.g. API_URL
try:
logger.info(f"Running Gradio UI command: {' '.join(cmd)}")
proc = subprocess.Popen(cmd, env=env)
logger.info(f"Gradio UI started (PID {proc.pid}). Access at http://{args.host or '127.0.0.1'}:{args.port}")
proc.wait()
if proc.returncode != 0:
logger.warning(f"Gradio exited with code {proc.returncode}")
return 0
except FileNotFoundError:
logger.error("Python executable or Gradio not found. Install gradio in your env.")
return 1
except Exception as e:
logger.error(f"Failed to start Gradio UI: {e}")
return 1
# Then simplify run_application():
...
if args.gradio_ui:
return start_gradio_ui(args, python_executable)
elif args.api_only:
...


try:
logger.info(f"Running Gradio UI command: {' '.join(cmd)}")
gradio_process = subprocess.Popen(cmd, env=env)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (dangerous-subprocess-use-audit): Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.

Source: opengrep

MasumRab added a commit that referenced this pull request Oct 29, 2025
feat: Add --gradio-ui option to launch.py
@MasumRab MasumRab deleted the feature/gradio-ui-launch branch November 1, 2025 07:28
MasumRab added a commit that referenced this pull request Nov 6, 2025
feat: Add --gradio-ui option to launch.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant