compression.py (3069B)
1 import modal 2 3 app = modal.App("compression") 4 vol = modal.Volume.from_name("compression", create_if_missing=True) 5 6 image = ( 7 modal.Image.debian_slim() 8 .apt_install(["git", "wget", "tar"]) 9 .run_commands( 10 [ 11 "wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64/cuda-keyring_1.1-1_all.deb", 12 "dpkg -i cuda-keyring_1.1-1_all.deb", 13 "apt-get update", 14 "apt-get -y install cuda-toolkit-12-8", 15 ] 16 ) 17 .env({"PATH": "/usr/local/cuda/bin:$PATH", "MODAL": "1"}) 18 .run_commands(["mkdir /scripts"]) 19 .add_local_file("scripts/smollm2", "/scripts/smollm2", copy=True) 20 .add_local_file("scripts/nacrith", "/scripts/nacrith", copy=True) 21 .run_commands(["chmod +x /scripts/smollm2", "/scripts/smollm2"]) 22 .run_commands(["chmod +x /scripts/nacrith", "/scripts/nacrith"]) 23 .pip_install("langchain-text-splitters") 24 ) 25 26 27 def run(commands): 28 import subprocess 29 import tempfile 30 import os 31 32 c = "\n".join(commands) 33 34 script = "\n".join(["#!/bin/bash", "set -e", c]) 35 36 with tempfile.NamedTemporaryFile(mode="w", suffix=".sh", delete=False) as f: 37 f.write(script) 38 path = f.name 39 40 os.chmod(path, 0o755) 41 42 try: 43 subprocess.run(["/bin/bash", path], check=False) 44 finally: 45 os.unlink(path) 46 47 48 @app.function(gpu="H100", image=image, volumes={"/data": vol}, timeout=600) 49 def compress(file_name): 50 run( 51 [ 52 "source /Nacrith-GPU/venv/bin/activate", 53 f'python /Nacrith-GPU/cli.py compress "/data/{file_name}" "/data/{file_name}.nc"', 54 ] 55 ) 56 57 58 @app.function(gpu="H100", image=image, volumes={"/data": vol}, timeout=600) 59 def decompress(file_name): 60 outfile = "".join(file_name.rsplit(".nc", 1)) 61 62 run( 63 [ 64 "source /Nacrith-GPU/venv/bin/activate", 65 f'python /Nacrith-GPU/cli.py decompress "/data/{file_name}" "/data/{outfile}"', 66 ] 67 ) 68 69 70 @app.function(image=image, volumes={"/data": vol}) 71 def batch(file_name: str, chunks: int = 20): 72 from langchain_text_splitters import RecursiveCharacterTextSplitter 73 import os 74 from pathlib import Path 75 76 input_file = f"/data/{file_name}" 77 78 with open(input_file, "r", encoding="utf-8") as f: 79 text = f.read() 80 81 text_splitter = RecursiveCharacterTextSplitter( 82 chunk_size=max(500, len(text) // chunks), 83 chunk_overlap=200, 84 length_function=len, 85 separators=["\n\n", "\n", ". ", " ", ""], 86 ) 87 88 text_chunks = text_splitter.split_text(text) 89 90 input_path = Path(input_file) 91 92 base_name = input_path.stem 93 94 ext = input_path.suffix or ".txt" 95 96 outputs = [] 97 98 for i, chunk in enumerate(text_chunks, 1): 99 output_file_name = f"{base_name}_chunk_{i:03d}{ext}" 100 101 output_file = f"/data/{output_file_name}" 102 103 with open(output_file, "w", encoding="utf-8") as f: 104 f.write(chunk) 105 106 outputs.append(output_file_name) 107 108 vol.commit() 109 110 for output_file_name in outputs: 111 compress.spawn(output_file_name)