✨ (CodeBlockExtractor.py): Add a new component 'Code Block Extractor' to extract code blocks from text for langflow application.

This commit is contained in:
ogabrielluiz 2024-06-07 14:40:39 -03:00
commit 578619a5e3
2 changed files with 29 additions and 4 deletions

View file

@ -0,0 +1,25 @@
import re
from langflow.custom import Component
from langflow.field_typing import Input, Output, Text
class CodeBlockExtractor(Component):
display_name = "Code Block Extractor"
description = "Extracts code block from text."
inputs = [Input(name="text", field_type=Text, description="Text to extract code blocks from.")]
outputs = [Output(name="code_block", display_name="Code Block", method="get_code_block")]
def get_code_block(self) -> Text:
text = self.text.strip()
# Extract code block
# It may start with ``` or ```language
# It may end with ```
pattern = r"^```(?:\w+)?\s*\n(.*?)(?=^```)```"
match = re.search(pattern, text, re.MULTILINE)
code_block = ""
if match:
code_block = match.group(1)
return code_block