Spaces:
Runtime error

Runnow / app.py
Nam Fam
update app.py
22dea69
Raw History Blame Contribute Delete
12 kB
import gradio as gr
import requests
import os
from dotenv import load_dotenv
load_dotenv()
MAX_OUTPUTS = 100
RUNNOW_ENDPOINT_URL = os.getenv("RUNNOW_ENDPOINT_URL")
DEFAULT_RUNNOW_API_KEY = os.getenv("RUNNOW_API_KEY") or ""
import base64
import io
def inference_interface(dependencies, code, api_key):
"""
Called when "Run" is clicked.
Calls the backend, then updates the UI state and filter.
"""
logs_content = ""
has_logs = False
variables = {}
audio_bytes, image_bytes, video_bytes = [], [], []
has_media = False
try:
# Use the provided API key if available, otherwise fallback to default
api_key = api_key or DEFAULT_RUNNOW_API_KEY
resp = requests.post(
RUNNOW_ENDPOINT_URL,
json={"dependencies": dependencies, "code": code},
headers={"x-api-key": api_key},
timeout=600 # Increased timeout for heavy installations
)
data = resp.json()
# Process logs and errors
if data.get("installation_logs", "").strip():
logs_content += f"### Installation Logs\n```\n{data['installation_logs']}\n```\n"
has_logs = True
if "error" in data:
logs_content += f"### 🚨 Error\n```\n{data['error']}\n```\n"
has_logs = True
# Consolidate user variables
if "locals" in data: variables.update(data["locals"])
if "result" in data: variables["result"] = data["result"]
# Process media files
media_files = data.get("media_files", [])
has_media = bool(media_files)
for mf in media_files:
fname, content = mf.get("filename", ""), mf.get("content", "")
ext = os.path.splitext(fname)[-1].lower()
try:
decoded_content = base64.b64decode(content)
if ext in [".wav", ".mp3", ".ogg", ".flac", ".m4a"]: audio_bytes.append(decoded_content)
elif ext in [".jpg", ".jpeg", ".png"]: image_bytes.append(decoded_content)
elif ext in [".mp4", ".webm"]: video_bytes.append(decoded_content)
except Exception: continue
# Add raw data to state for update_display to use
variables["_internal_logs_"] = logs_content
variables["_internal_media_files_"] = media_files
if "audio" in data: variables["audio"] = data["audio"] # Legacy
except Exception as e:
error_str = f"Request failed: {str(e)}"
variables = {"request_error": error_str}
logs_content = f"### 🚨 Request Error\n```\n{error_str}\n```\n"
has_logs = True
# Prepare all UI updates
all_var_names = list(variables.keys())
display_var_names = [k for k in all_var_names if not k.startswith('_internal_')]
# 1. Logs tab update
# Switch to the Logs tab if there are logs, otherwise stay on Output tab
logs_tab_update = gr.update(selected=1 if has_logs else 0)
logs_markdown_update = gr.update(value=logs_content if has_logs else "No logs to display.")
# 2. Media accordion and components update
media_accordion_update = gr.update(visible=has_media)
media_audio_updates = [gr.update(visible=i < len(audio_bytes), value=audio_bytes[i] if i < len(audio_bytes) else None) for i in range(5)]
media_image_updates = [gr.update(visible=i < len(image_bytes), value=image_bytes[i] if i < len(image_bytes) else None) for i in range(5)]
media_video_updates = [gr.update(visible=i < len(video_bytes), value=video_bytes[i] if i < len(video_bytes) else None) for i in range(3)]
# 3. Legacy audio output update
has_legacy_audio = "audio" in variables and variables["audio"]
legacy_audio_bytes = None
if has_legacy_audio:
try: legacy_audio_bytes = base64.b64decode(variables["audio"])
except: has_legacy_audio = False
audio_output_update = gr.update(value=legacy_audio_bytes, visible=has_legacy_audio)
# 4. Variable accordions update (initially all hidden, shown by filter)
accordion_updates = []
for i in range(MAX_OUTPUTS):
is_valid_var = i < len(all_var_names)
var_name = all_var_names[i] if is_valid_var else "Output"
value = f"```\n{str(variables.get(var_name, ''))}\n```" if is_valid_var else ""
accordion_updates.append(gr.update(label=var_name, visible=False))
accordion_updates.append(gr.update(value=value))
# Return all updates in the correct order
return [
variables, # State
gr.update(choices=display_var_names, value=[], visible=bool(display_var_names)), # Filter
logs_tab_update, # This is the update for the gr.Tabs container
gr.update(visible=False), # Default output
logs_markdown_update,
media_accordion_update,
*media_audio_updates,
*media_image_updates,
*media_video_updates,
audio_output_update,
*accordion_updates
]
def update_display(selected_vars, all_vars):
"""
Called when the filter selection changes.
Shows/hides variable accordions and keeps other components' state.
"""
updates = []
# Add an update for the default_output component to keep it hidden
updates.append(gr.update(visible=False))
# 1. Logs tab (preserve state)
logs_content = all_vars.get("_internal_logs_", "")
has_logs = bool(logs_content)
updates.append(gr.update(value=logs_content if has_logs else "No logs to display."))
# 2. Media components (preserve state)
media_files = all_vars.get("_internal_media_files_", [])
has_media = bool(media_files)
updates.append(gr.update(visible=has_media)) # Media accordion
audio_bytes, image_bytes, video_bytes = [], [], []
for mf in media_files:
content = mf.get("content", "")
ext = os.path.splitext(mf.get("filename", ""))[-1].lower()
try:
decoded_content = base64.b64decode(content)
if ext in [".wav", ".mp3", ".ogg", ".flac", ".m4a"]: audio_bytes.append(decoded_content)
elif ext in [".jpg", ".jpeg", ".png"]: image_bytes.append(decoded_content)
elif ext in [".mp4", ".webm"]: video_bytes.append(decoded_content)
except Exception: continue
updates.extend([gr.update(visible=i < len(audio_bytes), value=audio_bytes[i] if i < len(audio_bytes) else None) for i in range(5)])
updates.extend([gr.update(visible=i < len(image_bytes), value=image_bytes[i] if i < len(image_bytes) else None) for i in range(5)])
updates.extend([gr.update(visible=i < len(video_bytes), value=video_bytes[i] if i < len(video_bytes) else None) for i in range(3)])
# 3. Legacy audio (preserve state)
has_legacy_audio = "audio" in all_vars and all_vars["audio"]
legacy_audio_bytes = None
if has_legacy_audio:
try: legacy_audio_bytes = base64.b64decode(all_vars["audio"])
except: has_legacy_audio = False
updates.append(gr.update(value=legacy_audio_bytes, visible=has_legacy_audio))
# 4. Variable accordions (update based on selection)
all_var_names = list(all_vars.keys())
for i in range(MAX_OUTPUTS):
if i < len(all_var_names):
var_name = all_var_names[i]
is_visible = var_name in selected_vars
updates.append(gr.update(label=var_name, visible=is_visible))
value = f"```\n{str(all_vars.get(var_name, ''))}\n```" if is_visible else ""
updates.append(gr.update(value=value))
else:
updates.append(gr.update(visible=False))
updates.append(gr.update(value=""))
return tuple(updates)
example_code = '''import pandas as pd
# Create a sample DataFrame
data = {'col1': [1, 2, 3], 'col2': ['A', 'B', 'C']}
df = pd.DataFrame(data=data)
# You can also create other variables
my_variable = "This is a test with pandas."
'''
def build_ui():
custom_css = """
.output-container {
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
margin-top: 10px;
min-height: 200px;
height: 70vh;
background-color: #f9f9f9;
}
.output-container > *:first-child {
margin-top: 0;
}
"""
with gr.Blocks(title="RunNow: Instant Python Code Execution", css=custom_css) as demo:
gr.Markdown("# πŸš€ RunNow: Instant Python Code Execution\n\n")
with gr.Row():
with gr.Column(scale=1):
with gr.Accordion("πŸ”‘ API Key", open=False):
api_key_input = gr.Textbox(label="Runnow API Key", value=DEFAULT_RUNNOW_API_KEY, type="password", lines=1, placeholder="Enter your API key...")
dependencies_input = gr.Textbox(label="Dependencies", value="pip install pandas", lines=3, placeholder="pip install numpy\ngit clone https://github.com/user/repo.git")
code_input = gr.Textbox(label="Python Code", value=example_code, lines=30, show_copy_button=True, elem_id="code_input")
run_btn = gr.Button("Run", variant="primary")
with gr.Column(scale=2):
all_vars_state = gr.State(value={})
with gr.Column(elem_classes=["output-container"]):
variable_accordions = []
with gr.Tabs() as output_tabs:
with gr.TabItem("Output", id=0):
variable_filter = gr.CheckboxGroup(label="Choose Outputs to View", visible=False, interactive=True)
default_output = gr.Markdown("""
<div style='text-align: center; margin: 2rem; color: #666;'>
<p>πŸ‘‹ Welcome to RunNow!</p>
<p>Your output will appear here after running the code.</p>
<p>Click the \"Run\" button to execute your code.</p>
</div>
""")
with gr.Accordion("Media", visible=False) as media_accordion:
media_audio_outputs = [gr.Audio(label=f"Audio {i+1}", visible=False) for i in range(5)]
media_image_outputs = [gr.Image(label=f"Image {i+1}", visible=False) for i in range(5)]
media_video_outputs = [gr.Video(label=f"Video {i+1}", visible=False) for i in range(3)]
audio_output = gr.Audio(label="Audio Output", visible=False) # Legacy
for _ in range(MAX_OUTPUTS):
with gr.Accordion("Output", visible=False) as acc:
md = gr.Markdown()
variable_accordions.append(acc)
variable_accordions.append(md)
with gr.TabItem("Logs", id=1):
logs_markdown = gr.Markdown("No logs yet.")
output_components = [
default_output,
logs_markdown,
media_accordion,
*media_audio_outputs,
*media_image_outputs,
*media_video_outputs,
audio_output, # Legacy
*variable_accordions
]
run_btn.click(
fn=inference_interface,
inputs=[dependencies_input, code_input, api_key_input],
outputs=[all_vars_state, variable_filter, output_tabs, *output_components],
show_progress=True,
api_name="run_inference"
)
variable_filter.change(
fn=update_display,
inputs=[variable_filter, all_vars_state],
outputs=output_components
)
return demo
if __name__ == "__main__":
demo = build_ui()
demo.launch()