Spaces:
Runtime error
Runtime error
| 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> | |
| """ | |
| ) |