MCPcopy Create free account
hub / github.com/modelscope/ms-agent / extract_code_blocks

Function extract_code_blocks

projects/fin_research/callbacks/file_parser.py:5–39  ·  view source on GitHub ↗

Extract code blocks from the given text. ```py:a.py Args: text: The text to extract code blocks from. target_filename: The filename target to extract. Returns: Tuple: 0: The extracted code blocks. 1: The left content of the input text.

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

Source from the content-addressed store, hash-verified

3
4
5def extract_code_blocks(text: str,
6 target_filename: Optional[str] = None
7 ) -> Tuple[List, str]:
8 """Extract code blocks from the given text.
9
10 ```py:a.py
11
12 Args:
13 text: The text to extract code blocks from.
14 target_filename: The filename target to extract.
15
16 Returns:
17 Tuple:
18 0: The extracted code blocks.
19 1: The left content of the input text.
20 """
21 pattern = r'```[a-zA-Z]*:([^\n\r`]+)\n(.*?)```'
22 matches = re.findall(pattern, text, re.DOTALL)
23 result = []
24
25 for filename, code in matches:
26 filename = filename.strip()
27 if target_filename is None or filename == target_filename:
28 result.append({'filename': filename, 'code': code.strip()})
29
30 if target_filename is not None:
31 remove_pattern = rf'```[a-zA-Z]*:{re.escape(target_filename)}\n.*?```'
32 else:
33 remove_pattern = pattern
34
35 remaining_text = re.sub(remove_pattern, '', text, flags=re.DOTALL)
36 remaining_text = re.sub(r'\n\s*\n\s*\n', '\n\n', remaining_text)
37 remaining_text = remaining_text.strip()
38
39 return result, remaining_text

Callers 3

runMethod · 0.90
runMethod · 0.90
on_task_endMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected