Spaces:
Sleeping
Sleeping
File size: 2,198 Bytes
2f9e1f6 b98640a e7be0be b98640a e7be0be b98640a e7be0be b98640a e7be0be a2e04dd b98640a 2f9e1f6 | 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 | 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()
|