Spaces:
Sleeping
Sleeping
import jupytext | |
import os | |
import tempfile | |
def convert_file(input_file, output_format, config): | |
with tempfile.TemporaryDirectory() as temp_dir: | |
base_name = os.path.splitext(input_file.name)[0] | |
output_file = os.path.join(temp_dir, f"{base_name}.{output_format}") | |
content = input_file.getvalue() | |
input_format = os.path.splitext(input_file.name)[1][1:] | |
read_options = {} | |
write_options = {} | |
if input_format in ["py", "md"]: | |
read_options["fmt"] = f"{input_format}:{config['py_format']}" if input_format == "py" else input_format | |
notebook = jupytext.reads(content.decode(), **read_options) | |
else: | |
notebook = jupytext.reads(content, fmt=input_format) | |
if output_format == "py": | |
write_options["fmt"] = f"{output_format}:{config['py_format']}" | |
if config["comment_magics"]: | |
write_options["comment_magics"] = True | |
elif output_format == "ipynb": | |
write_options["fmt"] = output_format | |
else: | |
write_options["fmt"] = output_format | |
jupytext.write(notebook, output_file, **write_options) | |
with open(output_file, "rb") as f: | |
converted_content = f.read() | |
return converted_content, f"{base_name}.{output_format}" | |