import gradio as gr
from app import demo as app
import os
_docs = {'Log': {'description': '', 'members': {'__init__': {'level': {'type': '"INFO" | "DEBUG" | "WARNING" | "ERROR" | "CRITICAL"', 'description': None}, 'message': {'type': 'str', 'description': None}, 'timestamp': {'type': 'str', 'description': None}, 'return': {'type': 'None', 'description': None}}}}, '__meta__': {'additional_interfaces': {}}, 'LogsView': {'description': 'Creates a component to visualize logs from a subprocess in real-time.', 'members': {'__init__': {'value': {'type': 'str | Callable | tuple[str] | None', 'default': 'None', 'description': 'Default value to show in the code editor. If callable, the function will be called whenever the app loads to set the initial value of the component.'}, 'every': {'type': 'float | None', 'default': 'None', 'description': "If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute."}, 'lines': {'type': 'int', 'default': '5', 'description': None}, 'label': {'type': 'str | None', 'default': 'None', 'description': 'The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': 'minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': 'An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'render': {'type': 'bool', 'default': 'True', 'description': 'If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.'}}, 'postprocess': {'value': {'type': 'list[Log]', 'description': 'Expects a list of `Log` logs.'}}, 'preprocess': {'return': {'type': 'NoReturn', 'description': 'Passes the code entered as a `str`.'}, 'value': None}}, 'events': {'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the LogsView changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.'}, 'input': {'type': None, 'default': None, 'description': 'This listener is triggered when the user changes the value of the LogsView.'}, 'focus': {'type': None, 'default': None, 'description': 'This listener is triggered when the LogsView is focused.'}, 'blur': {'type': None, 'default': None, 'description': 'This listener is triggered when the LogsView is unfocused/blurred.'}}}, 'LogsViewRunner': {'description': 'Runner to execute a command or a function and capture logs in real-time.\n\n date_format: Date format to use for logs timestamps. Default is "%Y-%m-%d %H:%M:%S".\n\n date_format: Date format to use for logs timestamps.\n logs: List of `Log` logs.\n exit_code: Exit code of the process or function. None if not run yet.\n process: Process or subprocess.Popen object. None if not run yet.\n\n```python\nrunner = LogsViewRunner()\nfor logs in runner.run_command(["echo", "Hello World"]):\n for log in logs:\n print(log.timestamp, log.level, log.message)', 'members': {'__init__': {'date_format': {'type': 'str', 'default': '"%Y-%m-%d %H:%M:%S"', 'description': None}}}}}
abs_path = os.path.join(os.path.dirname(__file__), "css.css")
with gr.Blocks(
css=abs_path,
theme=gr.themes.Default(
font_mono=[
gr.themes.GoogleFont("Inconsolata"),
"monospace",
],
),
) as demo:
gr.Markdown(
"""
# `gradio_logsview`
Visualize logs in your Gradio app
""", elem_classes=["md-custom"], header_links=True)
app.render()
gr.Markdown(
"""
## Installation
```bash
pip install gradio_logsview
```
## Usage
```python
import logging
import random
import time
import gradio as gr
from gradio_logsview import LogsView, LogsViewRunner
from tqdm import tqdm
logger = logging.getLogger("custom.foo")
def random_values(failing: bool = False):
for i in tqdm(range(10)):
logger.log(
random.choice(
[ # Random levels
logging.INFO,
logging.DEBUG,
logging.WARNING,
logging.ERROR,
logging.CRITICAL,
]
),
f"Value {i+1}", # Random values
)
time.sleep(random.uniform(0, 1))
if failing and i == 5:
raise ValueError("Failing!!")
def fn_command_success():
runner = LogsViewRunner()
yield from runner.run_command(["python", "-u", "demo/script.py"])
yield runner.log(f"Runner: {runner}")
def fn_command_failing():
runner = LogsViewRunner()
yield from runner.run_command(["python", "-u", "demo/script.py", "--failing"])
yield runner.log(f"Runner: {runner}")
def fn_python_success():
runner = LogsViewRunner()
yield from runner.run_python(random_values, log_level=logging.INFO, logger_name="custom.foo", failing=False)
yield runner.log(f"Runner: {runner}")
def fn_python_failing():
runner = LogsViewRunner()
yield from runner.run_python(random_values, log_level=logging.INFO, logger_name="custom.foo", failing=True)
yield runner.log(f"Runner: {runner}")
markdown_top = \"\"\"
# LogsView Demo
This demo shows how to use the `LogsView` component to run some Python code or execute a command and display logs in real-time.
Click on any button to launch a process and see the logs displayed in real-time.
In the Python examples, code is executed in a process. You can see the logs (generated randomly with different log levels).
In the command examples, the command line is executed on the system directly. Any command can be executed.
\"\"\"
markdown_bottom = \"\"\"
## Installation
```
pip install https://huggingface.co/spaces/Wauplin/gradio_logsview/resolve/main/gradio_logsview-0.0.5-py3-none-any.whl
```
or add this line to your `requirements.txt`:
```
gradio_logsview@https://huggingface.co/spaces/Wauplin/gradio_logsview/resolve/main/gradio_logsview-0.0.5-py3-none-any.whl
```
## How to run Python code?
With `LogsView.run_python`, you can run Python code in a separate process and capture logs in real-time.
You can configure which logs to capture (log level and logger name).
```py
from gradio_logsview import LogsView
def fn_python():
# Run `my_function` in a separate process
# All logs above `INFO` level will be captured and displayed in real-time.
runner = LogsViewRunner() # Initialize the runner
yield from runner.run_python(my_function, log_level=logging.INFO, arg1="value1")
yield runner.log(f"Runner: {runner}") # Log any message
if runner.exit_code != 0:
# Handle error
...
with gr.Blocks() as demo:
logs = LogsView()
btn = gr.Button("Run Python code")
btn.click(fn_python, outputs=logs)
```
## How to run a command?
With `LogsView.run_command`, you can run a command on the system and capture logs from the process in real-time.
```py
from gradio_logsview import LogsView
def fn_command():
# Run a command and capture all logs from the subprocess
runner = LogsViewRunner() # Initialize the runner
yield from runner.run_command(
cmd=["mergekit-yaml", "config.yaml", "merge", "--copy-", "--cuda", "--low-cpu-memory"]
)
yield runner.log(f"Runner: {runner}") # Log any message
if runner.exit_code != 0:
# Handle error
...
with gr.Blocks() as demo:
logs = LogsView()
btn = gr.Button("Run command")
btn.click(fn_command, outputs=logs)
```
## TODO
- [ ] display logs with colors (front-end)
- [ ] format logs client-side (front-end)
- [ ] scrollable logs if more than N lines (front-end)
- [ ] format each log only once (front-end)
- [x] stop process if `run_command` gets cancelled (back-end)
- [x] correctly pass error stacktrace in `run_python` (back-end)
- [x] correctly catch print statements in `run_python` (back-end)
- [ ] disable interactivity + remove all code editing logic (both?)
- [x] how to handle progress bars? (i.e when logs are overwritten in terminal)
- [ ] Have 3 tabs in UI for stdout, stderr and logging (front-end + back-end)
- [ ] Write logger name in the logs (back-end)
\"\"\"
with gr.Blocks() as demo:
gr.Markdown(markdown_top)
with gr.Row():
btn_python_success = gr.Button("Run Python code (success)")
btn_python_failing = gr.Button("Run Python code (failing)")
with gr.Row():
btn_command_success = gr.Button("Run command (success)")
btn_command_failing = gr.Button("Run command (failing)")
logs = LogsView()
gr.Markdown(markdown_bottom)
btn_python_failing.click(fn_python_failing, outputs=logs)
btn_python_success.click(fn_python_success, outputs=logs)
btn_command_failing.click(fn_command_failing, outputs=logs)
btn_command_success.click(fn_command_success, outputs=logs)
if __name__ == "__main__":
demo.launch()
```
""", elem_classes=["md-custom"], header_links=True)
gr.Markdown("""
## `Log`
### Initialization
""", elem_classes=["md-custom"], header_links=True)
gr.ParamViewer(value=_docs["Log"]["members"]["__init__"], linkify=[])
gr.Markdown("""
## `LogsView`
### Initialization
""", elem_classes=["md-custom"], header_links=True)
gr.ParamViewer(value=_docs["LogsView"]["members"]["__init__"], linkify=[])
gr.Markdown("""
### User function
The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).
- When used as an Input, the component only impacts the input signature of the user function.
- When used as an output, the component only impacts the return signature of the user function.
The code snippet below is accurate in cases where the component is used as both an input and an output.
- **As input:** Is passed, passes the code entered as a `str`.
- **As output:** Should return, expects a list of `Log` logs.
```python
def predict(
value: NoReturn
) -> list[Log]:
return value
```
""", elem_classes=["md-custom", "LogsView-user-fn"], header_links=True)
gr.Markdown("""
## `LogsViewRunner`
### Initialization
""", elem_classes=["md-custom"], header_links=True)
gr.ParamViewer(value=_docs["LogsViewRunner"]["members"]["__init__"], linkify=[])
demo.load(None, js=r"""function() {
const refs = {};
const user_fn_refs = {};
requestAnimationFrame(() => {
Object.entries(user_fn_refs).forEach(([key, refs]) => {
if (refs.length > 0) {
const el = document.querySelector(`.${key}-user-fn`);
if (!el) return;
refs.forEach(ref => {
el.innerHTML = el.innerHTML.replace(
new RegExp("\\b"+ref+"\\b", "g"),
`${ref}`
);
})
}
})
Object.entries(refs).forEach(([key, refs]) => {
if (refs.length > 0) {
const el = document.querySelector(`.${key}`);
if (!el) return;
refs.forEach(ref => {
el.innerHTML = el.innerHTML.replace(
new RegExp("\\b"+ref+"\\b", "g"),
`${ref}`
);
})
}
})
})
}
""")
demo.launch()