| from typing import Dict, List, Any |
| import re |
|
|
| def _extract_section(text: str, start_marker: str, end_marker: str) -> str: |
| """Extract content between two markers""" |
| start = text.find(start_marker) |
| if start == -1: |
| return "" |
| start += len(start_marker) |
| end = text.find(end_marker, start) |
| if end == -1: |
| return "" |
| return text[start:end].strip() |
|
|
| class AnswerExtractor: |
| def __init__(self, task_name): |
| """Initialize answer extractor""" |
| self.task_name = task_name |
| |
| def extract_answers(self, response): |
| """Extract answers based on task type""" |
| try: |
| task_extractors = { |
| "S_0D": self.extract_S_0D, |
| "S_1D": self.extract_S_1D, |
| "S_Modification": self.extract_S_Modification, |
| "M_Birth": self.extract_M_Birth, |
| "M_Merge": self.extract_M_Merge, |
| "M_Filtration": self.extract_M_Filtration, |
| "H_Selection": self.extract_H_Selection, |
| "H_Generation": self.extract_H_Generation, |
| "R_Selection": self.extract_R_Selection, |
| "R_Generation": self.extract_R_Generation, |
| "R_Directly": self.extract_R_Directly |
| } |
| |
| answer = task_extractors.get(self.task_name)(response) if self.task_name in task_extractors else None |
| |
| return answer |
| except Exception as e: |
| print(f"Error extracting answer: {str(e)}") |
| return None |
| |
| |
| def extract_S_0D(self, answer: str) -> Dict[str, Any]: |
| """Extract information from 0-dimensional topology structure identification answer""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| value_match = re.search(r'connected components:\s*(\d+)', answer_section) |
| if not value_match: |
| return {"error": "connected components not found"} |
| |
| |
| try: |
| value = int(value_match.group(1).strip()) |
| return { |
| "connected_components": value |
| } |
| except ValueError as e: |
| return {"error": f"Error parsing value: {str(e)}"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
| def extract_S_1D(self, answer: str) -> Dict[str, Any]: |
| """Extract information from 1-dimensional topology structure identification answer""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| value_match = re.search(r'cycle holes:\s*(\d+)', answer_section) |
| if not value_match: |
| return {"error": "cycle holes not found"} |
| |
| |
| try: |
| value = int(value_match.group(1).strip()) |
| return { |
| "cycle_holes": value |
| } |
| except ValueError as e: |
| return {"error": f"Error parsing value: {str(e)}"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
|
|
|
|
| def extract_S_Modification(self, answer: str) -> Dict[str, Any]: |
| """Extract information from graph structure modification answer""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| patterns = [ |
| r'Edge to add:\s*\[(.*?)\]', |
| r'Edge to add:\s*\((\d+)\s*,\s*(\d+)\)', |
| r'Edge to add:\s*(\d+)\s*-\s*(\d+)', |
| r'Edge to add:\s*(\d+)\s*,\s*(\d+)' |
| ] |
| |
| for pattern in patterns: |
| value_match = re.search(pattern, answer_section) |
| if value_match: |
| try: |
| if pattern == r'Edge to add:\s*\[(.*?)\]': |
| |
| values_str = value_match.group(1).strip() |
| values = [int(x.strip()) for x in values_str.split(',')] |
| else: |
| |
| values = [int(value_match.group(1)), int(value_match.group(2))] |
| |
| return { |
| "edge_to_add": values |
| } |
| except (ValueError, IndexError): |
| continue |
| |
| return {"error": "Edge to add not found or invalid format"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
| |
| def extract_M_Birth(self, answer: str) -> Dict[str, Any]: |
| """Extract birth time calculation task answer""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| value_match = re.search(r'birth time:\s*\[(.*?)\]', answer_section) |
| if not value_match: |
| return {"error": "birth_time not found"} |
| |
| |
| try: |
| values = [self._parse_number(x) for x in value_match.group(1).split(',')] |
| return { |
| "birth_time": values |
| } |
| except ValueError as e: |
| return {"error": f"Error parsing : {str(e)}"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
|
|
| def extract_M_Merge(self, answer: str) -> Dict[str, Any]: |
| """Extract information from 0-dimensional persistent homology calculation task answer""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| value_match = re.search(r'death time:\s*\[(.*?)\]', answer_section) |
| if not value_match: |
| return {"error": "death_time not found"} |
| |
| |
| try: |
| values = [self._parse_number(x) for x in value_match.group(1).split(',')] |
| return { |
| "death_time": values |
| } |
| except ValueError as e: |
| return {"error": f"Error parsing : {str(e)}"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
| def extract_M_Filtration(self,answer:str) -> Dict[str, Any]: |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| value_match = re.search(r'connected components:\s*\[(.*?)\]', answer_section) |
| if not value_match: |
| return {"error": "connected components not found"} |
| |
| |
| try: |
| values = [self._parse_number(x) for x in value_match.group(1).split(',')] |
| return { |
| "connected_components": values |
| } |
| except ValueError as e: |
| return {"error": f"Error parsing : {str(e)}"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
|
|
| def extract_H_Selection(self, answer: str) -> Dict[str, Any]: |
| """Extract selected filtration method from the response""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| patterns = [ |
| r'Method:\s*([\w-]+)', |
| r'Method:\s*\[([\w-]+)\]', |
| r'selected_method:\s*([\w-]+)', |
| r'Selected Method:\s*([\w-]+)' |
| ] |
|
|
| for pattern in patterns: |
| value_match = re.search(pattern, answer_section, re.IGNORECASE) |
| if value_match: |
| method = value_match.group(1).strip().lower() |
| |
| valid_methods = ['degree', 'betweenness', 'k-shell', 'closeness', 'weight', 'eigenvector'] |
| if method in valid_methods: |
| return { |
| "selected_method": method |
| } |
|
|
| return {"error": "Method not found or invalid"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
|
|
|
|
| def extract_H_Generation(self, answer: str) -> Dict[str, Any]: |
| """Extract information from filteration value selection task answer""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| |
| |
| value_match = re.search(r'filtration value:\s*\[(.*?)\]', answer_section) |
| if not value_match: |
| return {"error": "Filtration value not found"} |
| |
| |
| try: |
| values = [int(x.strip()) for x in value_match.group(1).split(',')] |
| return { |
| "selected_filtration_values": values |
| } |
| except ValueError as e: |
| return {"error": f"Error parsing filtration values: {str(e)}"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
| def extract_filtration_edge_construction(self, answer: str) -> Dict[str, Any]: |
| """Extract information from filtration edge construction task answer""" |
| result = { |
| "filtration": {} |
| } |
| |
| try: |
| |
| filtration_section = _extract_section(answer, "===FILTRATION_START===", "===FILTRATION_END===") |
| result["filtration"] = self._parse_filtration_edges(filtration_section) |
| |
| |
| if not result["filtration"]: |
| print("Warning: Failed to extract filtration process") |
| print("Filtration process:", result["filtration"]) |
| |
| except Exception as e: |
| import traceback |
| print(f"Error during extraction: {str(e)}") |
| print("Error details:") |
| print(traceback.format_exc()) |
| return result |
| |
| return result |
| |
| def extract_simplicial_complex_construction(self, answer: str) -> Dict[str, Any]: |
| """ |
| Extract answer for simplicial_complex_construction task |
| |
| Parameters: |
| answer: Model generated answer text |
| |
| Returns: |
| dict: Contains extracted simplicial complex information |
| """ |
| try: |
| |
| simplex_text = self._extract_section(answer, "===SIMPLICIAL_COMPLEX_START===", "===SIMPLICIAL_COMPLEX_END===") |
| if not simplex_text: |
| return {"error": "Simplicial complex section not found"} |
| |
| |
| simplices = {} |
| |
| for line in simplex_text.split('\n'): |
| line = line.strip() |
| if not line: |
| continue |
| |
| |
| if line.startswith('[') and line.endswith(']'): |
| try: |
| |
| content = line[1:-1] |
| nodes_part, value_part = content.split('),') |
| nodes = [int(x.strip()) for x in nodes_part[1:].split(',')] |
| value = float(value_part.strip()) |
| |
| if len(nodes) == 3: |
| if value not in simplices: |
| simplices[value] = [] |
| simplices[value].append(nodes) |
| except (ValueError, IndexError) as e: |
| print(f"Error parsing simplex: {line}, error: {str(e)}") |
| continue |
| |
| return { |
| "simplicial_complexes": simplices |
| } |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
| def _parse_number(self, value_str: str) -> float: |
| """Parse number intelligently, try integer first, then float""" |
| value_str = value_str.strip() |
| try: |
| |
| return int(value_str) |
| except ValueError: |
| try: |
| |
| value = float(value_str) |
| |
| if value.is_integer(): |
| return int(value) |
| return value |
| except ValueError: |
| raise ValueError(f"Cannot parse number: {value_str}") |
|
|
| def extract_R_Selection(self, answer: str) -> Dict[str, Any]: |
| """Extract selected filtration method from the response""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
|
|
| |
| patterns = [ |
| r'Method:\s*(\w+)', |
| r'Method:\s*\[(.*?)\]', |
| r'selected_method:\s*(\w+)', |
| r'Selected Method:\s*(\w+)' |
| ] |
|
|
| for pattern in patterns: |
| value_match = re.search(pattern, answer_section, re.IGNORECASE) |
| if value_match: |
| method = value_match.group(1).strip().lower() |
| |
| valid_methods = ['degree', 'betweenness', 'k-shell', 'closeness', 'weight','eigenvector'] |
| if method in valid_methods: |
| return { |
| "selected_method": method |
| } |
|
|
| return {"error": "Method not found or invalid"} |
| |
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
|
|
| def extract_R_Generation(self, answer: str) -> Dict[str, Any]: |
| """Extract filtration values from the response""" |
| try: |
| |
| answer_section = answer |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
|
|
| |
| pattern = r'Filtration\s*value[s]?:\s*\[([^\]]+)\]' |
| match = re.search(pattern, answer_section, re.IGNORECASE) |
| if not match: |
| return {"error": "Filtration values not found"} |
|
|
| |
| nums_str = match.group(1) |
| values: List[float] = [] |
| for part in nums_str.split(','): |
| part = part.strip() |
| if part: |
| try: |
| values.append(float(part)) |
| except ValueError: |
| return {"error": f"Cannot convert '{part}' to float"} |
| |
| return {"filtration_values": values} |
|
|
| except Exception as e: |
| return {"error": f"Error during extraction: {str(e)}"} |
| |
| def extract_R_Directly(self, answer: str) -> Dict[str, Any]: |
| """Extract category classification from the response""" |
| |
| if "Answer:" in answer: |
| answer_section = answer.split("Answer:")[-1].strip() |
| else: |
| answer_section = answer |
| pattern = r'Category:\s*[\[\(]\s*([\d\.\s,]+)[\]\)]\s*,\s*[\[\(]\s*([\d\.\s,]+)[\]\)]' |
| match = re.search(pattern, answer_section, re.IGNORECASE | re.DOTALL) |
| if not match: |
| return {"error": "Category format not found or incorrect"} |
|
|
| def parse_group(group_str: str) -> List[int]: |
| return [int(float(x.strip())) for x in group_str.split(',') if x.strip()] |
|
|
| category1 = parse_group(match.group(1)) |
| category2 = parse_group(match.group(2)) |
|
|
| all_indices = sorted(category1 + category2) |
| if all_indices != [1, 2, 3, 4]: |
| return {"error": f"Graph indices must be [1, 2, 3, 4], got: {all_indices}"} |
|
|
| return { |
| "categories": [category1, category2] |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| |
|
|
|
|
| |
|
|