MCPcopy Create free account
hub / github.com/BUPT-GAMMA/MASFactory / extract_python_code

Function extract_python_code

applications/camel/eval/code_extractor.py:7–171  ·  view source on GitHub ↗

Extract Python code from text. Priority extraction: 1. Code block containing entry_point function 2. Python code in markdown code blocks 3. Directly included Python code Args: text: Text containing code. entry_point: Function entry point name (optio

(text: str, entry_point: Optional[str] = None)

Source from the content-addressed store, hash-verified

5
6
7def extract_python_code(text: str, entry_point: Optional[str] = None) -> str:
8 """
9 Extract Python code from text.
10
11 Priority extraction:
12 1. Code block containing entry_point function
13 2. Python code in markdown code blocks
14 3. Directly included Python code
15
16 Args:
17 text: Text containing code.
18 entry_point: Function entry point name (optional, for locating target function).
19
20 Returns:
21 Extracted Python code string.
22 """
23 if not text:
24 return ""
25
26 text = text.strip()
27
28 # If entry_point exists, try to extract code containing that function
29 if entry_point:
30 # Try to match code block containing entry_point
31 pattern = rf'(def\s+{re.escape(entry_point)}\s*\([^)]*\):.*?)(?=\n\ndef\s+|\nclass\s+|$)'
32 match = re.search(pattern, text, re.DOTALL)
33 if match:
34 code = match.group(1).strip()
35 # Ensure complete function body is included
36 if code.count('def') == 1:
37 # Try to find function end position (next def or class or end of file)
38 lines = text.split('\n')
39 start_idx = text.find(code)
40 if start_idx != -1:
41 start_line = text[:start_idx].count('\n')
42 # Find function definition line
43 for i, line in enumerate(lines[start_line:], start_line):
44 if line.strip().startswith(f'def {entry_point}'):
45 # Found function definition, extract to next def/class or end of file
46 code_lines = []
47 indent_level = None
48 for j in range(i, len(lines)):
49 current_line = lines[j]
50 if j == i:
51 code_lines.append(current_line)
52 # Determine function body indentation level
53 if ':' in current_line:
54 indent_level = len(current_line) - len(current_line.lstrip()) + 4
55 elif indent_level is not None:
56 # Check if it's part of function body
57 if current_line.strip() == '':
58 code_lines.append(current_line)
59 elif current_line.strip().startswith('#'):
60 code_lines.append(current_line)
61 elif len(current_line) - len(current_line.lstrip()) >= indent_level:
62 code_lines.append(current_line)
63 elif current_line.strip().startswith(('def ', 'class ')):
64 break

Callers 1

Calls 2

joinMethod · 0.80
matchMethod · 0.80

Tested by

no test coverage detected