Last active
May 26, 2025 12:25
-
-
Save OhadRubin/b2f81d1714707d5360e99d85d1b2dbea to your computer and use it in GitHub Desktop.
Python script to expand file contents with placeholders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example usage: | |
python3.10 expand.py template.md > expanded.md | |
This will expand all {file_path} placeholders in template.md with the actual file contents | |
and write the result to expanded.md | |
```template.md | |
You will be given several files, your goal is to convert the implementation. | |
<source_implementation> | |
{/path/to/source/file.py} | |
</source_implementation> | |
<target_framework> | |
{/path/to/target/framework/example.py} | |
</target_framework> | |
<reference_implementation> | |
{/path/to/reference/implementation.py} | |
</reference_implementation> | |
``` | |
""" | |
import re | |
import os | |
import fire | |
class PlaceholderEnumerator: | |
def __call__(self, match): | |
# match.group(1) is the content inside the braces | |
content = match.group(1) if match.group(1) else "" | |
assert os.path.isfile(content), f"File {content} does not exist" | |
with open(content, 'r', encoding='utf-8') as f: | |
file_content = f.read() | |
return file_content | |
def replace_w_enumerator(s): | |
enumerator = PlaceholderEnumerator() | |
result = re.sub(r"\{([^}]*)\}", enumerator, s) | |
return result | |
def expand_file(file_path): | |
with open(file_path, 'r') as file: | |
content = file.read() | |
print(replace_w_enumerator(content)) | |
# python3.10 expand.py bla.md > prompt.md | |
if __name__ == "__main__": | |
fire.Fire(expand_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment