Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
add view to select files
Abi Rajafd01d606a925
diff --git a/backend/evals/runner.py b/backend/evals/runner.pyindex 49bb7c25..d3080ad7 100644--- a/backend/evals/runner.py+++ b/backend/evals/runner.py@@ -39,12 +39,21 @@ async def generate_code_and_time(async def run_image_evals(- stack: Optional[Stack] = None, model: Optional[str] = None, n: int = 1+ stack: Optional[Stack] = None,+ model: Optional[str] = None,+ n: int = 1,+ input_files: Optional[List[str]] = None) -> List[str]:INPUT_DIR = EVALS_DIR + "/inputs"OUTPUT_DIR = EVALS_DIR + "/outputs"- evals = [f for f in os.listdir(INPUT_DIR) if f.endswith(".png")]+ # Get all evaluation image files+ if input_files and len(input_files) > 0:+ # Use the explicitly provided file list+ evals = [os.path.basename(f) for f in input_files if f.endswith(".png")]+ else:+ # Use all PNG files from the input directory+ evals = [f for f in os.listdir(INPUT_DIR) if f.endswith(".png")]if not stack:raise ValueError("No stack was provided")@@ -55,6 +64,11 @@ async def run_image_evals(print("User selected model:", model)selected_model = Llm(model)print(f"Running evals for {selected_model.value} model")++ if input_files and len(input_files) > 0:+ print(f"Running on {len(evals)} selected files")+ else:+ print(f"Running on all {len(evals)} files in {INPUT_DIR}")today = datetime.now().strftime("%b_%d_%Y")output_subfolder = os.path.join(@@ -70,7 +84,13 @@ async def run_image_evals(]] = []for original_filename in evals:- filepath = os.path.join(INPUT_DIR, original_filename)+ # Handle both full paths and relative filenames+ if os.path.isabs(original_filename):+ filepath = original_filename+ original_filename = os.path.basename(original_filename)+ else:+ filepath = os.path.join(INPUT_DIR, original_filename)+data_url = await image_to_data_url(filepath)for n_idx in range(n):current_model_for_task = (diff --git a/backend/routes/evals.py b/backend/routes/evals.pyindex a4cd347e..84714cfd 100644--- a/backend/routes/evals.py+++ b/backend/routes/evals.py@@ -22,6 +22,26 @@ class Eval(BaseModel):outputs: list[str]+class InputFile(BaseModel):+ name: str+ path: str++[email protected]("/eval_input_files", response_model=List[InputFile])+async def get_eval_input_files():+ """Get a list of all input files available for evaluations"""+ input_dir = os.path.join(EVALS_DIR, "inputs")+ try:+ files = []+ for filename in os.listdir(input_dir):+ if filename.endswith(".png"):+ file_path = os.path.join(input_dir, filename)+ files.append(InputFile(name=filename, path=file_path))+ return sorted(files, key=lambda x: x.name)+ except Exception as e:+ raise HTTPException(status_code=500, detail=f"Error reading input files: {str(e)}")++@router.get("/evals", response_model=list[Eval])async def get_evals(folder: str):if not folder:@@ -155,15 +175,20 @@ async def get_pairwise_evals(class RunEvalsRequest(BaseModel):models: List[str]stack: Stack+ files: List[str] = [] # Optional list of specific file paths to run evals on@router.post("/run_evals", response_model=List[str])async def run_evals(request: RunEvalsRequest) -> List[str]:- """Run evaluations on all images in the inputs directory for multiple models"""+ """Run evaluations on selected images in the inputs directory for multiple models"""all_output_files: List[str] = []for model in request.models:- output_files = await run_image_evals(model=model, stack=request.stack)+ output_files = await run_image_evals(+ model=model,+ stack=request.stack,+ input_files=request.files+ )all_output_files.extend(output_files)return all_output_filesdiff --git a/frontend/src/components/evals/InputFileSelector.tsx b/frontend/src/components/evals/InputFileSelector.tsxnew file mode 100644index 00000000..de524d54--- /dev/null+++ b/frontend/src/components/evals/InputFileSelector.tsx@@ -0,0 +1,129 @@+import { useState, useEffect } from "react";+import { HTTP_BACKEND_URL } from "../../config";+import { BsCheckLg } from "react-icons/bs";+import { Button } from "../ui/button";++interface InputFile {+ name: string;+ path: string;+}++interface InputFileSelectorProps {+ onFilesSelected: (files: string[]) => void;+}++function InputFileSelector({ onFilesSelected }: InputFileSelectorProps) {+ const [inputFiles, setInputFiles] = useState<InputFile[]>([]);+ const [selectedFiles, setSelectedFiles] = useState<string[]>([]);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ fetchInputFiles();+ }, []);++ const fetchInputFiles = async () => {+ setIsLoading(true);+ try {+ const response = await fetch(`${HTTP_BACKEND_URL}/eval_input_files`);+ if (!response.ok) {+ throw new Error("Failed to fetch input files");+ }++ const data = await response.json();+ setInputFiles(data);++ // 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 {+ setIsLoading(false);+ }+ };++ const handleFileToggle = (filePath: string) => {+ setSelectedFiles((prev) => {+ const newSelection = 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([]);+ };++ if (isLoading) {+ return <div className="text-center">Loading input files...</div>;+ }++ return (+ <div className="w-full max-w-md">+ <div className="border rounded-md p-2 space-y-2 max-h-80 overflow-y-auto">+ {inputFiles.map((file) => (+ <div+ key={file.path}+ className={`flex items-center justify-between p-2 rounded cursor-pointer hover:bg-gray-50 ${+ selectedFiles.includes(file.path)+ ? "bg-blue-50 border border-blue-200"+ : ""+ }`}+ onClick={() => handleFileToggle(file.path)}+ >+ <span className="text-sm truncate" title={file.name}>+ {file.name}+ </span>+ {selectedFiles.includes(file.path) ? (+ <BsCheckLg className="h-4 w-4 text-blue-500" />+ ) : (+ <div className="h-4 w-4 border rounded-sm" />+ )}+ </div>+ ))}+ </div>++ <div className="flex justify-between mt-2">+ <p className="text-sm text-gray-500">+ Selected: {selectedFiles.length} file+ {selectedFiles.length !== 1 ? "s" : ""}+ </p>+ <div className="space-x-2">+ {selectedFiles.length < inputFiles.length && (+ <Button+ variant="ghost"+ size="sm"+ onClick={handleSelectAll}+ className="text-sm text-gray-500 hover:text-gray-700"+ >+ Select all+ </Button>+ )}+ {selectedFiles.length > 0 && (+ <Button+ variant="ghost"+ size="sm"+ onClick={handleClearAll}+ className="text-sm text-gray-500 hover:text-gray-700"+ >+ Clear all+ </Button>+ )}+ </div>+ </div>+ </div>+ );+}++export default InputFileSelector;diff --git a/frontend/src/components/evals/RunEvalsPage.tsx b/frontend/src/components/evals/RunEvalsPage.tsxindex 75052930..c5a74cf8 100644--- a/frontend/src/components/evals/RunEvalsPage.tsx+++ b/frontend/src/components/evals/RunEvalsPage.tsx@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";import { Button } from "../ui/button";import { HTTP_BACKEND_URL } from "../../config";import { BsCheckLg } from "react-icons/bs";+import InputFileSelector from "./InputFileSelector";interface ModelResponse {models: string[];@@ -14,6 +15,7 @@ function RunEvalsPage() {const [stacks, setStacks] = useState<string[]>([]);const [selectedModels, setSelectedModels] = useState<string[]>([]);const [selectedStack, setSelectedStack] = useState<string>("html_tailwind");+ const [selectedFiles, setSelectedFiles] = useState<string[]>([]);useEffect(() => {const fetchModels = async () => {@@ -44,6 +46,7 @@ function RunEvalsPage() {body: JSON.stringify({models: selectedModels,stack: selectedStack,+ files: selectedFiles,}),});@@ -79,6 +82,10 @@ function RunEvalsPage() {setSelectedModels(models);};+ const handleFilesSelected = (files: string[]) => {+ setSelectedFiles(files);+ };+return (<div className="flex flex-col items-center justify-center min-h-screen"><h1 className="text-2xl font-bold mb-8">Run Evaluations</h1>@@ -98,7 +105,7 @@ function RunEvalsPage() {</p></div>- <div className="space-y-4 w-full max-w-md">+ <div className="space-y-6 w-full max-w-md"><div><label className="block text-gray-700 text-sm font-bold mb-2">Select Models@@ -170,11 +177,18 @@ function RunEvalsPage() {))}</select></div>++ <div>+ <label className="block text-gray-700 text-sm font-bold mb-2">+ Select Input Files+ </label>+ <InputFileSelector onFilesSelected={handleFilesSelected} />+ </div></div><ButtononClick={runEvals}- disabled={isRunning || selectedModels.length === 0}+ disabled={isRunning || selectedModels.length === 0 || selectedFiles.length === 0}className="w-48 mt-6">{isRunning ? "Running Evals..." : "Run Evals"}