Spaces:
Runtime error
Runtime error
File size: 11,402 Bytes
a34ed73 94b8264 94badb1 a34ed73 94b8264 94badb1 a34ed73 94badb1 a34ed73 94badb1 a34ed73 94badb1 94b8264 94badb1 a34ed73 94badb1 94b8264 94badb1 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 94badb1 94b8264 94badb1 94b8264 94badb1 a34ed73 94badb1 94b8264 a34ed73 94badb1 a34ed73 94badb1 a34ed73 94b8264 a34ed73 94badb1 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 94b8264 a34ed73 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
import gradio as gr
import random
import time
from datetime import datetime
import tempfile
import os
import traceback
def safe_write_temp_file(content: str, suffix: str = ".txt") -> str | None:
"""
Safely writes content to a temporary file.
Returns the file path if successful, None otherwise.
"""
try:
# Create a temp file that persists after closing (delete=False)
# We use a try/finally block to ensure we close the file handle
# before returning the path, preventing OS locking errors.
temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=suffix)
temp_file.write(content)
temp_file.close()
return temp_file.name
except IOError as e:
print(f"File System Error: {e}")
return None
except Exception as e:
print(f"Unexpected File Error: {e}")
return None
def simulate_processing(
content: str,
operation: str,
iteration: int,
creativity_level: float
) -> tuple[str, int, str, gr.DownloadButton | None]:
"""
Simulates a Review, Revise, Refactor, and Iterate workflow.
Includes comprehensive error handling.
"""
# 1. Initial Validation (Double check, though validator handles the first pass)
if content is None:
return "", 0, "β οΈ **Error:** No input detected.", None
try:
# Simulate processing time based on creativity level
# Capped to prevent excessive waiting
delay = min(0.3 + (creativity_level * 0.5), 2.0)
time.sleep(delay)
result = content
status_msg = ""
download_filename = None
# Generate a timestamp for logs
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if operation == "Review":
status_msg = f"""
### β
Review Complete
- **Status:** Pass
- **Time:** {timestamp}
- **Analysis:** Syntax looks valid.
- **Suggestion:** Consider adding docstrings and type hints for better maintainability.
"""
result = f"# REVIEW LOG [{timestamp}]\n# Status: Pass\n# Note: Code structure is solid.\n\n{content}"
download_filename = "review_log.py"
elif operation == "Revise":
status_msg = """
### βοΈ Revision Complete
- **Tone:** Professional
- **Grammar:** Corrected
- **Flow:** Optimized
"""
# Logic: Ensure we handle string operations safely
sentences = content.split('. ')
revised = '. '.join([s.strip().capitalize() for s in sentences if s.strip()])
result = revised if revised else content
download_filename = "revised_text.txt"
elif operation == "Refactor":
status_msg = """
### βοΈ Refactoring Complete
- **Optimization:** Applied
- **Complexity:** Reduced
- **Style:** PEP8 Compliant
"""
# Logic: Safe string replacement
result = content.replace("var ", "let ").replace(" ", " ")
result = f"# REFACTORED VERSION [{timestamp}]\n# Optimized for performance\n{result}"
download_filename = "refactored_code.py"
elif operation == "Iterate":
iteration += 1
status_msg = f"""
### π Iteration {iteration} Generated
- **Creativity Level:** {creativity_level:.2f}
- **Action:** Created new version based on feedback.
"""
result = f"# --- ITERATION {iteration} ---\n# Generated at {timestamp}\n# Creativity: {creativity_level}\n{content}"
download_filename = f"iteration_{iteration}.py"
# 2. File Generation with Error Handling
temp_file_path = None
if result:
temp_file_path = safe_write_temp_file(result, ".txt")
if not temp_file_path:
# If file write failed, warn the user but don't crash the whole app
status_msg += "\n\nβ οΈ **Warning:** Could not generate download file due to a system error."
# 3. Return success state
# We return an updated DownloadButton component
return result, iteration, status_msg, gr.DownloadButton(value=temp_file_path, visible=True)
except Exception as e:
# 4. Global Exception Catch
# This catches any unexpected crashes in the logic above
error_trace = traceback.format_exc()
print(f"Critical Error in Processing: {error_trace}")
error_msg = f"""
### π¨ Critical Error
The workflow encountered an unexpected error.
**Error Details:** `{str(e)}`
*Your input has been preserved. Please try again or check your input format.*
"""
# Return error state (no download button, preserve input)
return content, iteration, error_msg, gr.DownloadButton(visible=False, value=None)
def validate_inputs(content: str, operation: str):
"""
Gradio 6 Validator function.
Runs immediately on the client side before queuing.
"""
if not content or not content.strip():
return [
gr.validate(False, "Input cannot be empty. Please enter text or code to proceed.")
]
return [gr.validate(True)] # Valid
# Gradio 6 Application
# NO parameters in gr.Blocks() constructor!
with gr.Blocks() as demo:
# Professional Header
gr.HTML("""
<div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #f0fdf4 0%, #ecfeff 100%); border-radius: 12px; margin-bottom: 25px; border: 1px solid #ccfbf1;">
<h1 style="margin: 0; color: #0f172a; font-family: 'Inter', sans-serif;">π Studio Workflow Engine</h1>
<p style="margin: 10px 0 0 0; color: #64748b; font-size: 1.1em;">Professional Review, Revise, Refactor, and Iteration Tool</p>
<div style="margin-top: 15px;">
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank"
style="background-color: #10b981; color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 0.9em; box-shadow: 0 2px 4px rgba(16, 185, 129, 0.2);">
Built with anycoder
</a>
</div>
</div>
""")
with gr.Sidebar(position="left", width=320):
gr.Markdown("### π οΈ Control Panel")
with gr.Group():
operation_mode = gr.Radio(
choices=["Review", "Revise", "Refactor", "Iterate"],
value="Review",
label="Operation Mode",
info="Select the workflow stage."
)
with gr.Accordion("βοΈ Advanced Settings", open=False):
creativity = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.1,
label="Creativity Level",
info="Simulates AI randomness"
)
iteration_state = gr.Number(value=0, label="Current Iteration", interactive=False)
gr.Markdown("---")
gr.Markdown("### π Workflow Guide")
gr.Markdown("""
1. **Review**: Analyze syntax and structure.
2. **Revise**: Improve phrasing and tone.
3. **Refactor**: Optimize code structure.
4. **Iterate**: Create a new version copy.
""")
with gr.Row():
with gr.Column(scale=1):
input_code = gr.Code(
label="Input Source",
language="python",
placeholder="Paste your code or text here...",
lines=20,
show_label=True
)
with gr.Row():
clear_btn = gr.Button("Clear Workspace", variant="secondary", scale=1, size="lg")
run_btn = gr.Button("Execute Workflow", variant="primary", scale=2, size="lg")
# Examples Section
gr.Markdown("### π‘ Quick Start Examples")
gr.Examples(
examples=[
["def hello():\n print('Hello World')", "Review"],
["this is a poorly written sentence. it needs help.", "Revise"],
["var x = 10;\nvar y = 20;\nreturn x + y;", "Refactor"],
],
inputs=[input_code, operation_mode],
label="Try these samples:"
)
with gr.Column(scale=1):
status_output = gr.Markdown(label="Process Log", value="*Ready to process...*")
output_code = gr.Code(
label="Result Output",
language="python",
lines=18,
interactive=True
)
# Initialize download button as hidden
download_btn = gr.DownloadButton(
label="π₯ Download Result",
variant="secondary",
visible=False,
size="lg"
)
# Event Listeners using Gradio 6 syntax
# 1. Main Execution Event
# We attach the validator here to check inputs before running the heavy function
run_btn.click(
fn=simulate_processing,
validator=validate_inputs,
inputs=[input_code, operation_mode, iteration_state, creativity],
outputs=[output_code, iteration_state, status_output, download_btn],
api_visibility="public"
)
# 2. Clear Button Event
clear_btn.click(
fn=lambda: (
"", # input_code
0, # iteration_state
"*Ready to process...*", # status_output
gr.DownloadButton(visible=False, value=None), # download_btn
"Review", # operation_mode
0.5 # creativity
),
inputs=None,
outputs=[input_code, iteration_state, status_output, download_btn, operation_mode, creativity],
api_visibility="private"
)
# NOTE: Removed output_code.change listener to prevent file generation loops/locks.
# The download button is now exclusively updated by the Execute Workflow button.
# Gradio 6 Launch Configuration
# ALL app-level parameters (theme, css, etc.) go here!
demo.launch(
theme=gr.themes.Soft(
primary_hue="emerald",
secondary_hue="teal",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter"),
text_size="md",
spacing_size="lg",
radius_size="md"
).set(
button_primary_background_fill="*primary_600",
button_primary_background_fill_hover="*primary_700",
button_primary_text_color="white",
button_secondary_background_fill="*neutral_100",
block_border_width="1px",
block_border_color="*neutral_200",
body_background_fill="*background_fill_primary",
shadow_drop="lg",
),
footer_links=[
{"label": "Documentation", "url": "https://www.gradio.app/docs"},
{"label": "GitHub", "url": "https://github.com/gradio-app/gradio"},
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
],
head="""
<style>
.gradio-container {
max-width: 1400px !important;
}
</style>
"""
) |