Spaces:
Build error
Build error
Update app.py
Browse files911 unmodified lines912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960326 unmodified lines12871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396911 unmodified linesreturn final_answerdef parse_grid_from_response(query: str) -> List[List[int]]:# Initialize ARC componentsarc_loader = ARCDataLoader()arc_converter = ARCTaskConverter()arc_evaluator = ARCEvaluator()"""Parse the grid from the agent's response string."""try:# Look for grid pattern in the responsegrid_lines = []in_grid = Falsefor line in query.split('\n'):# Start collecting grid when we see a row patternif '[' in line and ']' in line and any(c.isdigit() for c in line):in_grid = True# Clean the line and extract numbersclean_line = line.strip().strip('[]').replace(',', ' ')row = [int(x) for x in clean_line.split() if x.isdigit()]if row:grid_lines.append(row)# Stop if we've found the grid and hit a non-grid lineelif in_grid and line.strip() and '[' not in line:break# Validate grid formatif not grid_lines:raise ValueError("No valid grid found in response")# Ensure all rows have same lengthwidth = len(grid_lines[0])if not all(len(row) == width for row in grid_lines):raise ValueError("Inconsistent grid row lengths")# Ensure all values are 0, 3, or 8 (based on training data)valid_values = {0, 3, 8}if not all(all(val in valid_values for val in row) for row in grid_lines):raise ValueError("Invalid grid values found")return grid_linesexcept Exception as e:print(f"Error parsing grid: {str(e)}")return Nonedef process_query(task_json: str) -> str:# Initialize ARC components326 unmodified lineswith open(os.path.join(eval_path, filename), 'r') as f:tasks.append((filename, json.load(f)))return tasksdef process_all_tasks() -> Any:"""Process all evaluation tasks sequentially with progress tracking."""try:# Initialize system componentsarc_loader = ARCDataLoader()arc_evaluator = ARCEvaluator()tasks = load_evaluation_tasks()total_tasks = len(tasks)results = []progress = gr.Progress()progress(0, desc="Initializing...")for idx, (filename, task) in enumerate(tasks):try:# Update progressprogress((idx / total_tasks),desc=f"Processing task {idx + 1}/{total_tasks}: {filename}")# Process current task directly without string conversionpredicted_grids = []success = False# Process each test casefor test_idx, test_case in enumerate(task['test']):for trial in range(3): # 3 trials per test casetry:# Generate prediction using the agent systempredicted_grid = generate_prediction(train_pairs=task['train'],test_input=test_case['input'],trial=trial)if predicted_grid:success = arc_evaluator.evaluate_output(predicted_grid,test_case['output'])predicted_grids.append(predicted_grid)if success:break # Stop trials if successfulexcept Exception as e:print(f"Trial {trial + 1} failed: {str(e)}")continue# Format task resultstask_result = f"\nTask {idx + 1}/{total_tasks}: {filename}\n"task_result += "=" * 50 + "\n"task_result += f"Success: {success}\n\n"# Add training examplestask_result += "Training Examples:\n"for train_idx, train_pair in enumerate(task['train']):task_result += f"\nExample {train_idx + 1}:\n"task_result += "Input:\n"task_result += grid_to_string(train_pair['input']) + "\n"task_result += "Output:\n"task_result += grid_to_string(train_pair['output']) + "\n"# Add test resultstask_result += "\nTest Results:\n"for test_idx, (test_case, pred_grid) in enumerate(zip(task['test'], predicted_grids)):task_result += f"\nTest Case {test_idx + 1}:\n"task_result += "Input:\n"task_result += grid_to_string(test_case['input']) + "\n"task_result += "Expected Output:\n"task_result += grid_to_string(test_case['output']) + "\n"task_result += "Predicted Output:\n"task_result += grid_to_string(pred_grid) + "\n"task_result += "=" * 50 + "\n"results.append(task_result)# Record result for evaluationarc_evaluator.record_result(filename, idx + 1, success)# Yield intermediate resultsyield "\n".join(results)except Exception as e:error_msg = f"\nError processing {filename}: {str(e)}\n"results.append(error_msg)yield "\n".join(results)# Final progress updateprogress(1.0, desc="Processing complete!")# Generate and add final summarysummary = arc_evaluator.get_summary()summary_text = "\nEvaluation Complete!\n"summary_text += f"Total tasks processed: {total_tasks}\n"summary_text += f"Successful tasks: {summary['successful_tasks']}\n"summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n"summary_text += f"Average trials to success: {summary['average_trials_to_success']:.2f}\n"results.append(summary_text)yield "\n".join(results)except Exception as e:yield f"Fatal error during task processing: {str(e)}"def grid_to_string(grid: List[List[int]]) -> str:"""Convert a grid to a formatted string representation."""911 unmodified lines91291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007326 unmodified lines133413351336133713381339911 unmodified linesreturn final_answerdef parse_grid_from_response(response: str) -> List[List[int]]:"""Parse the grid from the agent's response string.Args:response: String containing the agent's responseReturns:List[List[int]]: Parsed grid or None if parsing fails"""try:# Look for grid pattern in the responsegrid_lines = []in_grid = Falsefor line in response.split('\n'):# Start collecting grid when we see a row patternif '[' in line and ']' in line and any(c.isdigit() for c in line):in_grid = True# Clean the line and extract numbersclean_line = line.strip().strip('[]').replace(',', ' ')row = [int(x) for x in clean_line.split() if x.isdigit()]if row:grid_lines.append(row)# Stop if we've found the grid and hit a non-grid lineelif in_grid and line.strip() and '[' not in line:break# Validate grid formatif not grid_lines:raise ValueError("No valid grid found in response")# Ensure all rows have same lengthwidth = len(grid_lines[0])if not all(len(row) == width for row in grid_lines):raise ValueError("Inconsistent grid row lengths")# Ensure all values are 0-9if not all(all(0 <= val <= 9 for val in row) for row in grid_lines):raise ValueError("Invalid grid values found")return grid_linesexcept Exception as e:print(f"Error parsing grid: {str(e)}")return Nonedef process_all_tasks() -> Iterator[str]:"""Process all evaluation tasks sequentially with progress tracking.Returns:Iterator[str]: Yields status updates and results as strings"""try:tasks = load_evaluation_tasks()total_tasks = len(tasks)results = []progress = gr.Progress()progress(0, desc="Initializing...")for idx, (filename, task) in enumerate(tasks):try:progress((idx / total_tasks),desc=f"Processing task {idx + 1}/{total_tasks}: {filename}")# Process task and get resultstask_result = process_query(task) # Now passing task dict directlyresults.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}")yield "\n".join(results)except Exception as e:error_msg = f"\nError processing {filename}: {str(e)}\n"results.append(error_msg)yield "\n".join(results)progress(1.0, desc="Processing complete!")# Add final summarysummary = arc_evaluator.get_summary()summary_text = "\nEvaluation Complete!\n"summary_text += f"Total tasks processed: {total_tasks}\n"summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n"results.append(summary_text)yield "\n".join(results)except Exception as e:yield f"Fatal error during task processing: {str(e)}"def process_query(task_json: str) -> str:# Initialize ARC components326 unmodified lineswith open(os.path.join(eval_path, filename), 'r') as f:tasks.append((filename, json.load(f)))return tasksdef grid_to_string(grid: List[List[int]]) -> str:"""Convert a grid to a formatted string representation."""
app.py+86-143