File size: 1,618 Bytes
9fbf50e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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?