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("""
Professional Review, Revise, Refactor, and Iteration Tool