Download evaluate_code/extract.py from Antislab/LLM4PH: direct link, hf CLI and curl.
- Browser
- Download file 26.2 kB
-
https://huggingface.co/datasets/Antislab/LLM4PH/resolve/main/evaluate_code/extract.py
- Command line
-
hf download hf://datasets/Antislab/LLM4PH/evaluate_code/extract.py
-
curl -L -o extract.py https://huggingface.co/datasets/Antislab/LLM4PH/resolve/main/evaluate_code/extract.py
26.2 kB
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Extract the filtration value with more flexible pattern matching | |
| value_match = re.search(r'connected components:\s*(\d+)', answer_section) | |
| if not value_match: | |
| return {"error": "connected components not found"} | |
| # Parse the value | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Extract the filtration value with more flexible pattern matching | |
| value_match = re.search(r'cycle holes:\s*(\d+)', answer_section) | |
| if not value_match: | |
| return {"error": "cycle holes not found"} | |
| # Parse the value | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Try multiple matching patterns | |
| patterns = [ | |
| r'Edge to add:\s*\[(.*?)\]', # Match "Edge to add: [0, 7]" format | |
| r'Edge to add:\s*\((\d+)\s*,\s*(\d+)\)', # Match "Edge to add: (0, 7)" format | |
| r'Edge to add:\s*(\d+)\s*-\s*(\d+)', # Match "Edge to add: 0-7" format | |
| r'Edge to add:\s*(\d+)\s*,\s*(\d+)' # Match "Edge to add: 0, 7" format | |
| ] | |
| for pattern in patterns: | |
| value_match = re.search(pattern, answer_section) | |
| if value_match: | |
| try: | |
| if pattern == r'Edge to add:\s*\[(.*?)\]': | |
| # Handle [0, 7] format | |
| values_str = value_match.group(1).strip() | |
| values = [int(x.strip()) for x in values_str.split(',')] | |
| else: | |
| # Handle other formats | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Extract the filtration value | |
| value_match = re.search(r'birth time:\s*\[(.*?)\]', answer_section) | |
| if not value_match: | |
| return {"error": "birth_time not found"} | |
| # Parse the values | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Extract the filtration value | |
| value_match = re.search(r'death time:\s*\[(.*?)\]', answer_section) | |
| if not value_match: | |
| return {"error": "death_time not found"} | |
| # Parse the values | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Extract the filtration value | |
| value_match = re.search(r'connected components:\s*\[(.*?)\]', answer_section) | |
| if not value_match: | |
| return {"error": "connected components not found"} | |
| # Parse the values | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Try multiple matching patterns | |
| patterns = [ | |
| r'Method:\s*([\w-]+)', # Match "Method: k-shell" format | |
| r'Method:\s*\[([\w-]+)\]', # Match "Method: [k-shell]" format | |
| r'selected_method:\s*([\w-]+)', # Match "selected_method: k-shell" format | |
| r'Selected Method:\s*([\w-]+)' # Match "Selected Method: k-shell" format | |
| ] | |
| for pattern in patterns: | |
| value_match = re.search(pattern, answer_section, re.IGNORECASE) | |
| if value_match: | |
| method = value_match.group(1).strip().lower() | |
| # Validate method name | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Extract the filtration value | |
| value_match = re.search(r'filtration value:\s*\[(.*?)\]', answer_section) | |
| if not value_match: | |
| return {"error": "Filtration value not found"} | |
| # Parse the values | |
| 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: | |
| # Extract filtration process | |
| filtration_section = _extract_section(answer, "===FILTRATION_START===", "===FILTRATION_END===") | |
| result["filtration"] = self._parse_filtration_edges(filtration_section) | |
| # Validate results | |
| 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 partially parsed results instead of None | |
| 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: | |
| # Extract simplicial complex section | |
| simplex_text = self._extract_section(answer, "===SIMPLICIAL_COMPLEX_START===", "===SIMPLICIAL_COMPLEX_END===") | |
| if not simplex_text: | |
| return {"error": "Simplicial complex section not found"} | |
| # Parse simplicial complex | |
| simplices = {} | |
| for line in simplex_text.split('\n'): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| # Check if it's a simplex | |
| if line.startswith('[') and line.endswith(']'): | |
| try: | |
| # Parse node list and filtration value | |
| content = line[1:-1] # Remove outer brackets | |
| nodes_part, value_part = content.split('),') | |
| nodes = [int(x.strip()) for x in nodes_part[1:].split(',')] # Remove inner brackets | |
| value = float(value_part.strip()) | |
| if len(nodes) == 3: # Only process 2-dimensional simplices (triangles) | |
| 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: | |
| # Try parsing as integer first | |
| return int(value_str) | |
| except ValueError: | |
| try: | |
| # If integer parsing fails, try parsing as float | |
| value = float(value_str) | |
| # If it's an integer (no decimal part), return integer | |
| 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: | |
| # Extract the answer section | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Try multiple matching patterns | |
| patterns = [ | |
| r'Method:\s*(\w+)', # Match "Method: weight" format | |
| r'Method:\s*\[(.*?)\]', # Match "Method: [weight]" format | |
| r'selected_method:\s*(\w+)', # Match "selected_method: weight" format | |
| r'Selected Method:\s*(\w+)' # Match "Selected Method: weight" format | |
| ] | |
| 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: | |
| # Extract content after "Answer:" if present | |
| answer_section = answer | |
| if "Answer:" in answer: | |
| answer_section = answer.split("Answer:")[-1].strip() | |
| # Match pattern like Filtration value: [0.1,0.4,0.5,...] | |
| pattern = r'Filtration\s*value[s]?:\s*\[([^\]]+)\]' | |
| match = re.search(pattern, answer_section, re.IGNORECASE) | |
| if not match: | |
| return {"error": "Filtration values not found"} | |
| # Extract numbers inside brackets, split by comma and convert to float | |
| 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""" | |
| # Get content after "Answer:" if present | |
| 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] | |
| } | |
| # def _parse_filtration_edges(self, section: str) -> Dict[float, List[Tuple[int, int]]]: | |
| # """Parse filtration process, specific to the format of filtration edge construction task""" | |
| # filtration = {} | |
| # current_value = None | |
| # for line in section.split('\n'): | |
| # line = line.strip() | |
| # if line.startswith('**Value='): | |
| # value_part = line.replace('**', '').replace('Value=', '').strip() | |
| # current_value = float(value_part) | |
| # filtration[current_value] = [] | |
| # elif line.startswith('(') and line.endswith(')'): | |
| # try: | |
| # u, v = map(int, line[1:-1].split(',')) | |
| # filtration[current_value].append((u, v)) | |
| # except: | |
| # print(f"Cannot parse edge: {line}") | |
| # return filtration | |
| # def extract_structure_identification(self, answer: str) -> Dict[str, Any]: | |
| # """Extract information from topology structure identification answer""" | |
| # result = { | |
| # "cavities": [], | |
| # "temporal_evolution": {} | |
| # } | |
| # # Extract cavity information | |
| # if "2-DIMENSIONAL CAVITIES:" in answer: | |
| # cavities_section = self._extract_section( | |
| # answer, "2-DIMENSIONAL CAVITIES:", "TEMPORAL EVOLUTION:" | |
| # ) | |
| # result["cavities"] = self._extract_cavities(cavities_section) | |
| # # Extract temporal evolution | |
| # if "TEMPORAL EVOLUTION:" in answer: | |
| # evolution_section = answer.split("TEMPORAL EVOLUTION:")[1] | |
| # result["temporal_evolution"] = self._extract_temporal_evolution(evolution_section) | |
| # return result | |
| # def extract_simplex_structure_identification(self, answer: str) -> Dict[str, Any]: | |
| # """Extract information from simplex structure identification answer""" | |
| # result = { | |
| # "simplex_count": 0 | |
| # } | |
| # lines = answer.strip().split('\n') | |
| # for line in lines: | |
| # line = line.strip() | |
| # if line.startswith('2维单纯形数量:'): | |
| # count_str = line.split(':')[1].strip() | |
| # try: | |
| # result["simplex_count"] = int(count_str) | |
| # except ValueError: | |
| # # Keep default value 0 if cannot parse as integer | |
| # pass | |
| # return result | |
| # def _extract_section(self, text: str, start_marker: str, end_marker: str) -> str: | |
| # """Extract text between two markers""" | |
| # if start_marker in text and end_marker in text: | |
| # start_idx = text.find(start_marker) + len(start_marker) | |
| # end_idx = text.find(end_marker) | |
| # return text[start_idx:end_idx].strip() | |
| # return "" | |
| # def _extract_list(self, text: str) -> List: | |
| # """Extract list from text""" | |
| # items = text.split(':')[1].strip() | |
| # if items.startswith('[') and items.endswith(']'): | |
| # return eval(items) | |
| # return [] | |
| # def _extract_feature_info(self, line: str) -> Dict[str, Any]: | |
| # """Extract feature information from text""" | |
| # info = {} | |
| # if 'Birth time:' in line: | |
| # info['birth'] = float(line.split(':')[1].strip()) | |
| # elif 'Death time:' in line: | |
| # info['death'] = float(line.split(':')[1].strip()) | |
| # elif 'Persistence:' in line: | |
| # info['persistence'] = float(line.split(':')[1].strip()) | |
| # elif 'Description:' in line: | |
| # info['description'] = line.split(':')[1].strip() | |
| # return info | |
| # def _extract_cavities(self, text: str) -> List[Dict[str, Any]]: | |
| # """Extract cavity information""" | |
| # cavities = [] | |
| # current_cavity = None | |
| # for line in text.split('\n'): | |
| # if line.startswith('Cavity'): | |
| # if current_cavity: | |
| # cavities.append(current_cavity) | |
| # current_cavity = {} | |
| # elif current_cavity is not None and line.startswith('-'): | |
| # key = line.split(':')[0].strip('- ').lower() | |
| # value = line.split(':')[1].strip() | |
| # if key in ['birth threshold', 'death threshold', 'persistence']: | |
| # value = float(value) | |
| # elif key in ['nodes', 'edges']: | |
| # value = eval(value) | |
| # current_cavity[key] = value | |
| # if current_cavity: | |
| # cavities.append(current_cavity) | |
| # return cavities | |
| # def _extract_temporal_evolution(self, text: str) -> Dict[float, Dict[str, List[int]]]: | |
| # """Extract temporal evolution information""" | |
| # evolution = {} | |
| # current_threshold = None | |
| # for line in text.split('\n'): | |
| # if line.startswith('Threshold'): | |
| # current_threshold = float(line.split()[1]) | |
| # evolution[current_threshold] = { | |
| # 'active': [], | |
| # 'new': [], | |
| # 'disappeared': [] | |
| # } | |
| # elif current_threshold is not None and line.startswith('-'): | |
| # key = line.split(':')[0].strip('- ').lower() | |
| # value = eval(line.split(':')[1].strip()) | |
| # evolution[current_threshold][key] = value | |
| # return evolution | |
| # def _extract_current_state(self, text: str) -> Dict[str, Any]: | |
| # """Extract current state information""" | |
| # state = {} | |
| # for line in text.split('\n'): | |
| # if line.startswith('- Number of cycles:'): | |
| # state['cycles'] = int(line.split(':')[1].strip()) | |
| # elif line.startswith('- Cycle locations:'): | |
| # state['locations'] = eval(line.split(':')[1].strip()) | |
| # return state | |
| # def _extract_proposed_modifications(self, text: str) -> List[Dict[str, Any]]: | |
| # """Extract proposed modifications""" | |
| # modifications = [] | |
| # current_mod = None | |
| # for line in text.split('\n'): | |
| # if line.startswith('Modification'): | |
| # if current_mod: | |
| # modifications.append(current_mod) | |
| # current_mod = {} | |
| # elif current_mod is not None and line.startswith('-'): | |
| # key = line.split(':')[0].strip('- ').lower() | |
| # value = line.split(':')[1].strip() | |
| # if key == 'new edge': | |
| # value = tuple(map(int, value.split('-'))) | |
| # elif key == 'expected new cycles': | |
| # value = eval(value) | |
| # current_mod[key] = value | |
| # if current_mod: | |
| # modifications.append(current_mod) | |
| # return modifications | |
| # def _extract_expected_outcome(self, text: str) -> Dict[str, Any]: | |
| # """Extract expected outcome""" | |
| # outcome = {} | |
| # for line in text.split('\n'): | |
| # if line.startswith('- New number of cycles:'): | |
| # outcome['new_cycles'] = int(line.split(':')[1].strip()) | |
| # elif line.startswith('- New cycle locations:'): | |
| # outcome['new_locations'] = eval(line.split(':')[1].strip()) | |
| # elif line.startswith('- Changes in persistence:'): | |
| # outcome['persistence_changes'] = line.split(':')[1].strip() | |
| # return outcome | |