codeboosterstech's picture
Upload 9 files
9fbf50e verified
raw
history blame
1.62 kB
import zipfile
import io
import json
def create_zip_archive(files: dict) -> bytes:
"""Creates a zip archive in memory from a dictionary of filename: content."""
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for filename, content in files.items():
zip_file.writestr(filename, content)
zip_buffer.seek(0)
return zip_buffer.getvalue()
def read_file_content(file_obj) -> str:
"""Reads content from a file object (GradIO file wrapper) or path."""
if hasattr(file_obj, 'name'):
path = file_obj.name
else:
path = file_obj
try:
with open(path, 'r', encoding='utf-8') as f:
return f.read()
except UnicodeDecodeError:
# Fallback for some notebook formats if needed
with open(path, 'r', encoding='latin-1') as f:
return f.read()
def extract_code_from_ipynb(ipynb_content: str) -> str:
"""Extracts code cells from ipynb json string."""
try:
data = json.loads(ipynb_content)
code_cells = []
for cell in data.get('cells', []):
if cell.get('cell_type') == 'code':
source = cell.get('source', [])
if isinstance(source, list):
code_cells.append(''.join(source))
elif isinstance(source, str):
code_cells.append(source)
return '\n\n'.join(code_cells)
except json.JSONDecodeError:
return ipynb_content # Validation failed or not json, treat as raw text?