Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| import google.generativeai as genai | |
| from datetime import datetime | |
| # --- Configure Gemini --- | |
| genai.configure(api_key=os.environ["GEMINI_API_KEY"]) | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| # --- Recursive Executor Function --- | |
| def recursive_executor(task, max_attempts=3): | |
| logs = [] | |
| code_output = "" | |
| for attempt in range(1, max_attempts + 1): | |
| logs.append(f"\n--- Attempt {attempt} ---") | |
| try: | |
| response = model.generate_content( | |
| f"Write Python code to solve this task:\n{task}" | |
| ) | |
| code_output = response.text.strip() | |
| # β quick validation: does it at least contain 'def' or 'print' | |
| if "def " in code_output or "print(" in code_output: | |
| logs.append("β Code looks valid, stopping recursion.") | |
| break | |
| else: | |
| logs.append("β οΈ Code seems incomplete, retrying...") | |
| except Exception as e: | |
| logs.append(f"β Error: {str(e)}") | |
| if not code_output: | |
| code_output = "# No valid code generated." | |
| return code_output, "\n".join(logs) | |
| # --- Download Logs --- | |
| def save_logs(log_text): | |
| filename = f"logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" | |
| with open(filename, "w", encoding="utf-8") as f: | |
| f.write(log_text) | |
| return filename | |
| # --- Gradio Interface --- | |
| with gr.Blocks(theme="soft") as demo: | |
| gr.Markdown("## π Recursive Executor with Logs & Code Viewer") | |
| task_input = gr.Textbox( | |
| placeholder="Enter a programming task...", | |
| label="Task" | |
| ) | |
| run_btn = gr.Button("Run Executor") | |
| code_output = gr.Code(label="Generated Code", language="python") | |
| logs_output = gr.Textbox(label="Execution Logs", lines=15) | |
| download_btn = gr.Button("Download Logs") | |
| file_output = gr.File(label="Log File") | |
| def run_executor(task): | |
| code, logs = recursive_executor(task) | |
| return code, logs | |
| run_btn.click(run_executor, inputs=task_input, outputs=[code_output, logs_output]) | |
| download_btn.click(save_logs, inputs=logs_output, outputs=file_output) | |
| if __name__ == "__main__": | |
| demo.launch() | |