Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Add rerun-on-failure support

Abi Raja36e3e9e982fd
diff --git a/backend/evals/runner.py b/backend/evals/runner.py
index 9dcf4f29..4a0c96b6 100644
--- a/backend/evals/runner.py
+++ b/backend/evals/runner.py
@@ -10,6 +10,7 @@ from .core import generate_code_for_image
from .utils import image_to_data_url
from .config import EVALS_DIR
+MAX_EVAL_RETRIES = 2
async def generate_code_and_time(
image_url: str,
@@ -17,26 +18,50 @@ async def generate_code_and_time(
model: Llm,
original_input_filename: str,
attempt_idx: int,
-) -> Tuple[str, int, Optional[str], Optional[float], Optional[Exception]]:
+) -> Tuple[str, int, Optional[str], Optional[float], Optional[Exception], int]:
"""
Generates code for an image, measures the time taken, and returns identifiers
along with success/failure status.
- Returns a tuple: (original_input_filename, attempt_idx, content, duration, error_object)
+ Returns a tuple:
+ (original_input_filename, attempt_idx, content, duration, error_object, retries_used)
content and duration are None if an error occurs during generation.
"""
- start_time = time.perf_counter()
- try:
- content = await generate_code_for_image(
- image_url=image_url, stack=stack, model=model
- )
- end_time = time.perf_counter()
- duration = end_time - start_time
- return original_input_filename, attempt_idx, content, duration, None
- except Exception as e:
- print(
- f"Error during code generation for {original_input_filename} (attempt {attempt_idx}): {e}"
- )
- return original_input_filename, attempt_idx, None, None, e
+ retries_used = 0
+ while True:
+ start_time = time.perf_counter()
+ try:
+ content = await generate_code_for_image(
+ image_url=image_url, stack=stack, model=model
+ )
+ end_time = time.perf_counter()
+ duration = end_time - start_time
+ return (
+ original_input_filename,
+ attempt_idx,
+ content,
+ duration,
+ None,
+ retries_used,
+ )
+ except Exception as e:
+ if retries_used >= MAX_EVAL_RETRIES:
+ print(
+ f"Error during code generation for {original_input_filename} "
+ f"(attempt {attempt_idx}, retries exhausted): {e}"
+ )
+ return (
+ original_input_filename,
+ attempt_idx,
+ None,
+ None,
+ e,
+ retries_used,
+ )
+ retries_used += 1
+ print(
+ f"Retrying {original_input_filename} (attempt {attempt_idx}) "
+ f"{retries_used}/{MAX_EVAL_RETRIES} after error: {e}"
+ )
async def run_image_evals(
@@ -82,7 +107,7 @@ async def run_image_evals(
Coroutine[
Any,
Any,
- Tuple[str, int, Optional[str], Optional[float], Optional[Exception]],
+ Tuple[str, int, Optional[str], Optional[float], Optional[Exception], int],
]
] = []
for original_filename in evals:
@@ -124,9 +149,14 @@ async def run_image_evals(
for future in asyncio.as_completed(task_coroutines):
try:
- task_orig_fn, task_attempt_idx, generated_content, time_taken, error_obj = (
- await future
- )
+ (
+ task_orig_fn,
+ task_attempt_idx,
+ generated_content,
+ time_taken,
+ error_obj,
+ retries_used,
+ ) = await future
completed_tasks += 1
output_html_filename_base = os.path.splitext(task_orig_fn)[0]
@@ -139,7 +169,9 @@ async def run_image_evals(
if error_obj is not None:
failed_tasks_log.append(
- f"Input: {task_orig_fn}, Attempt: {task_attempt_idx}, OutputFile: {final_output_html_filename}, Error: Generation failed - {str(error_obj)}"
+ f"Input: {task_orig_fn}, Attempt: {task_attempt_idx}, OutputFile: "
+ f"{final_output_html_filename}, Retries: {retries_used}, "
+ f"Error: Generation failed - {str(error_obj)}"
)
await emit_progress(
{
@@ -150,6 +182,7 @@ async def run_image_evals(
"attempt_idx": task_attempt_idx,
"success": False,
"error": str(error_obj),
+ "retries_used": retries_used,
}
)
elif generated_content is not None and time_taken is not None:
@@ -173,6 +206,7 @@ async def run_image_evals(
"success": True,
"output_file": final_output_html_filename,
"duration_seconds": time_taken,
+ "retries_used": retries_used,
}
)
except Exception as e_write:
diff --git a/frontend/src/components/evals/InputFileSelector.tsx b/frontend/src/components/evals/InputFileSelector.tsx
index 906aed2f..df1e7e8b 100644
--- a/frontend/src/components/evals/InputFileSelector.tsx
+++ b/frontend/src/components/evals/InputFileSelector.tsx
@@ -22,6 +22,10 @@ function InputFileSelector({ onFilesSelected }: InputFileSelectorProps) {
fetchInputFiles();
}, []);
+ useEffect(() => {
+ onFilesSelected(selectedFiles);
+ }, [selectedFiles, onFilesSelected]);
+
const fetchInputFiles = async () => {
setIsLoading(true);
try {
@@ -36,7 +40,6 @@ function InputFileSelector({ onFilesSelected }: InputFileSelectorProps) {
// By default, select all files
const allFilePaths = data.map((file: InputFile) => file.path);
setSelectedFiles(allFilePaths);
- onFilesSelected(allFilePaths);
} catch (error) {
console.error("Error fetching input files:", error);
} finally {
@@ -46,24 +49,19 @@ function InputFileSelector({ onFilesSelected }: InputFileSelectorProps) {
const handleFileToggle = (filePath: string) => {
setSelectedFiles((prev) => {
- const newSelection = prev.includes(filePath)
+ return prev.includes(filePath)
? prev.filter((path) => path !== filePath)
: [...prev, filePath];
-
- onFilesSelected(newSelection);
- return newSelection;
});
};
const handleSelectAll = () => {
const allFilePaths = inputFiles.map((file) => file.path);
setSelectedFiles(allFilePaths);
- onFilesSelected(allFilePaths);
};
const handleClearAll = () => {
setSelectedFiles([]);
- onFilesSelected([]);
};
const toggleExpanded = () => {
diff --git a/frontend/src/components/evals/RunEvalsPage.tsx b/frontend/src/components/evals/RunEvalsPage.tsx
index 78159c45..6710e95f 100644
--- a/frontend/src/components/evals/RunEvalsPage.tsx
+++ b/frontend/src/components/evals/RunEvalsPage.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from "react";
+import { useState, useEffect, useCallback } from "react";
import { Button } from "../ui/button";
import { Progress } from "../ui/progress";
import { HTTP_BACKEND_URL } from "../../config";
@@ -23,9 +23,16 @@ interface EvalProgressEvent {
global_total_tasks?: number;
input_file?: string;
success?: boolean;
+ error?: string;
output_files?: string[];
}
+interface FailedTask {
+ model: string;
+ inputFile: string;
+ error: string;
+}
+
function RunEvalsPage() {
const [isRunning, setIsRunning] = useState(false);
const [models, setModels] = useState<string[]>([]);
@@ -40,6 +47,7 @@ function RunEvalsPage() {
const [statusMessage, setStatusMessage] = useState<string>("Idle");
const [lastProcessedFile, setLastProcessedFile] = useState<string>("");
const [failedTasks, setFailedTasks] = useState(0);
+ const [failedTaskDetails, setFailedTaskDetails] = useState<FailedTask[]>([]);
useEffect(() => {
const fetchModels = async () => {
@@ -57,7 +65,7 @@ function RunEvalsPage() {
};
}, []);
- const runEvals = async () => {
+ const runEvals = async (filesToRun?: string[]) => {
const updateRunningTitle = (completed: number, total: number) => {
if (total <= 0) {
document.title = "Running Evals...";
@@ -76,6 +84,9 @@ function RunEvalsPage() {
setStatusMessage("Preparing evaluation run...");
setLastProcessedFile("");
setFailedTasks(0);
+ setFailedTaskDetails([]);
+
+ const runFiles = filesToRun ?? selectedFiles;
const response = await fetch(`${HTTP_BACKEND_URL}/run_evals_stream`, {
method: "POST",
@@ -85,7 +96,7 @@ function RunEvalsPage() {
body: JSON.stringify({
models: selectedModels,
stack: selectedStack,
- files: selectedFiles,
+ files: runFiles,
}),
});
@@ -101,9 +112,13 @@ function RunEvalsPage() {
const decoder = new TextDecoder();
let bufferedText = "";
- while (true) {
+ let streamDone = false;
+ while (!streamDone) {
const { value, done } = await reader.read();
- if (done) break;
+ if (done) {
+ streamDone = true;
+ continue;
+ }
bufferedText += decoder.decode(value, { stream: true });
const lines = bufferedText.split("\n");
@@ -131,6 +146,14 @@ function RunEvalsPage() {
if (event.input_file) setLastProcessedFile(event.input_file);
if (event.success === false) {
setFailedTasks((prev) => prev + 1);
+ setFailedTaskDetails((prev) => [
+ ...prev,
+ {
+ model: event.model ?? "unknown",
+ inputFile: event.input_file ?? "unknown",
+ error: event.error ?? "Unknown error",
+ },
+ ]);
}
setStatusMessage(
event.success === false
@@ -178,9 +201,9 @@ function RunEvalsPage() {
setSelectedModels(models);
};
- const handleFilesSelected = (files: string[]) => {
+ const handleFilesSelected = useCallback((files: string[]) => {
setSelectedFiles(files);
- };
+ }, []);
// Format model list for display in the summary
const formatModelList = () => {
@@ -191,6 +214,13 @@ function RunEvalsPage() {
};
const canRunEvals = selectedModels.length > 0 && selectedFiles.length > 0;
+ const failedFilesForRerun = Array.from(
+ new Set(failedTaskDetails.map((task) => task.inputFile).filter(Boolean))
+ );
+ const canRerunFailures =
+ !isRunning &&
+ selectedModels.length > 0 &&
+ failedFilesForRerun.length > 0;
const progressPercent = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
return (
@@ -205,7 +235,7 @@ function RunEvalsPage() {
<h1 className="text-2xl font-bold">Run Evaluations</h1>
<Button
- onClick={runEvals}
+ onClick={() => void runEvals()}
disabled={isRunning || !canRunEvals}
className={`min-w-[120px] ${isRunning ? "bg-blue-400" : "bg-blue-600 hover:bg-blue-700"}`}
>
@@ -277,6 +307,41 @@ function RunEvalsPage() {
<span className="font-mono">{lastProcessedFile || "-"}</span>
</span>
</div>
+ {failedTaskDetails.length > 0 && (
+ <div className="mt-3 border-t border-gray-100 pt-3">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-sm font-medium text-red-700">
+ Failures ({failedTaskDetails.length})
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!canRerunFailures}
+ onClick={() => void runEvals(failedFilesForRerun)}
+ className="h-7 px-2 text-xs"
+ >
+ Re-run failures
+ </Button>
+ </div>
+ <div className="max-h-40 overflow-y-auto rounded-md border border-red-100 bg-red-50/40">
+ <ul className="divide-y divide-red-100">
+ {failedTaskDetails.map((task, index) => (
+ <li key={`${task.model}-${task.inputFile}-${index}`} className="px-3 py-2 text-xs">
+ <div className="font-medium text-red-800">
+ {task.inputFile}
+ </div>
+ <div className="text-red-700">
+ Model: <span className="font-mono">{task.model}</span>
+ </div>
+ <div className="text-red-700 break-words">
+ Error: {task.error}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ )}
</div>
)}
</div>