File size: 9,775 Bytes
0eb334a
ae8e699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0eb334a
ae8e699
 
 
 
 
 
 
 
 
 
 
0eb334a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae8e699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0eb334a
 
 
 
 
 
 
ae8e699
0eb334a
 
 
 
ae8e699
 
 
0eb334a
ae8e699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0eb334a
ae8e699
0eb334a
 
 
 
 
 
 
 
 
ae8e699
 
 
0eb334a
ae8e699
0eb334a
ae8e699
0eb334a
 
 
 
 
 
 
 
ae8e699
 
0eb334a
ae8e699
 
 
 
 
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

import os
import re
import time
import tempfile
import shutil
from pathlib import Path
from huggingface_hub import hf_hub_download, upload_file, list_repo_files
from fastapi import FastAPI
from contextlib import asynccontextmanager
import asyncio
import logging

try:
    import rarfile
except ImportError:
    rarfile = None

# === CONFIGURATION ===
HF_TOKEN = os.environ.get("HF_TOKEN")
REPO_ID = "factorstudios/Pipeline"
DATA_PATH = "Blenders"
EXTRACTED_PATH = "Blenders/extracted"
TEMP_DIR = tempfile.gettempdir()

# === Setup Logging ===
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

app = FastAPI()

# === Health Check Routes ===
@app.get("/")
def root():
    return {"status": "RAR Extractor running"}

@app.get("/health")
def health():
    return {"healthy": True}

# === Get Course Name from Filename ===
def extract_course_name(filename: str) -> str:
    """Extract course name from RAR filename"""
    name = os.path.splitext(filename)[0]
    # Remove common patterns like .part1, .001, etc
    name = re.sub(r'\.(part\d+|r\d+|\d+)$', '', name, flags=re.IGNORECASE)
    return name

# === Download File from Dataset ===
def download_from_dataset(filename: str, repo_path: str) -> str:
    try:
        logging.info(f"[*] Downloading from dataset: {repo_path}/{filename}")
        local_path = hf_hub_download(
            repo_id=REPO_ID,
            filename=f"{repo_path}/{filename}",
            repo_type="dataset",
            token=HF_TOKEN,
            cache_dir=TEMP_DIR
        )
        logging.info(f"[βœ“] Downloaded: {filename}")
        return local_path
    except Exception as e:
        logging.error(f"[!] Download failed: {filename} β€” {e}")
        return None

# === Extract RAR File ===
def extract_rar(rar_path: str, extract_dir: str) -> bool:
    try:
        if rarfile is None:
            logging.error("[!] rarfile module not installed. Install with: pip install rarfile")
            return False
        
        logging.info(f"[*] Extracting RAR: {os.path.basename(rar_path)}")
        with rarfile.RarFile(rar_path) as rf:
            rf.extractall(extract_dir)
        logging.info(f"[βœ“] Extracted to: {extract_dir}")
        return True
    except Exception as e:
        logging.error(f"[!] RAR extraction failed: {rar_path} β€” {e}")
        return False

# === Upload Directory Contents to Dataset ===
def upload_directory_to_dataset(local_dir: str, dataset_path: str) -> bool:
    try:
        file_count = 0
        for root, dirs, files in os.walk(local_dir):
            for file in files:
                filepath = os.path.join(root, file)
                relative_path = os.path.relpath(filepath, local_dir)
                remote_path = f"{dataset_path}/{relative_path}".replace("\\", "/")
                
                upload_file(
                    path_or_fileobj=filepath,
                    path_in_repo=remote_path,
                    repo_id=REPO_ID,
                    repo_type="dataset",
                    token=HF_TOKEN
                )
                logging.info(f"[↑] Uploaded: {remote_path}")
                file_count += 1
        
        logging.info(f"[βœ“] Uploaded {file_count} files to {dataset_path}")
        return True
    except Exception as e:
        logging.error(f"[!] Upload directory failed: {local_dir} β€” {e}")
        return False

# === List RAR Files in Dataset ===
def list_rar_files_in_dataset() -> list:
    try:
        logging.info(f"[*] Scanning dataset for RAR files in {DATA_PATH}")
        all_files = list_repo_files(
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN
        )
        
        rar_files = [
            f for f in all_files 
            if f.startswith(DATA_PATH) 
            and (f.lower().endswith(".rar") or re.search(r'\.r\d{2}$', f, re.IGNORECASE))
        ]
        
        logging.info(f"[*] Found {len(rar_files)} RAR files")
        for rf in rar_files:
            logging.info(f"    - {rf}")
        
        return rar_files
    except Exception as e:
        logging.error(f"[!] Failed to list files: {e}")
        return []

# === List Extracted Courses in Dataset ===
def list_extracted_courses_in_dataset() -> set:
    try:
        logging.info(f"[*] Scanning dataset for extracted courses in {EXTRACTED_PATH}")
        all_files = list_repo_files(
            repo_id=REPO_ID,
            repo_type="dataset",
            token=HF_TOKEN
        )
        
        extracted_courses = set()
        for f in all_files:
            if f.startswith(EXTRACTED_PATH + '/') and len(f.split('/')) > len(EXTRACTED_PATH.split('/')):
                # Extract the course name from the path
                course_name = f.split('/')[len(EXTRACTED_PATH.split('/'))]
                extracted_courses.add(course_name)
        
        logging.info(f"[*] Found {len(extracted_courses)} extracted courses")
        for ec in extracted_courses:
            logging.info(f"    - {ec}")
            
        return extracted_courses
    except Exception as e:
        logging.error(f"[!] Failed to list extracted courses: {e}")
        return set()

# === Extract and Upload RAR ===
async def extract_and_upload_rar(rar_file_path: str):
    try:
        # Get filename
        filename = os.path.basename(rar_file_path)
        course_name = extract_course_name(filename)
        
        # Create temp extraction directory
        extract_dir = os.path.join(TEMP_DIR, f"rar_extract_{int(time.time())}")
        os.makedirs(extract_dir, exist_ok=True)
        
        logging.info(f"[*] Processing: {filename} (Course: {course_name})")
        
        # Download RAR file
        local_rar = download_from_dataset(filename, DATA_PATH)
        if not local_rar:
            return False
        
        # Extract RAR
        if not extract_rar(local_rar, extract_dir):
            shutil.rmtree(extract_dir, ignore_errors=True)
            return False
        
        # Upload to dataset under blenders/extracted/{course_name}
        remote_path = f"{EXTRACTED_PATH}/{course_name}"
        if not upload_directory_to_dataset(extract_dir, remote_path):
            shutil.rmtree(extract_dir, ignore_errors=True)
            return False
        
        # Cleanup
        shutil.rmtree(extract_dir, ignore_errors=True)
        logging.info(f"[βœ“] Completed: {course_name}")
        return True
        
    except Exception as e:
        logging.error(f"[!] Error processing {rar_file_path}: {e}")
        return False

# === Background Worker ===
async def rar_processor_worker():
    logging.info("πŸš€ RAR Processor started")
    while True:
        try:
            logging.info("[*] Scanning for RAR files...")
            rar_files = list_rar_files_in_dataset()
            extracted_courses = list_extracted_courses_in_dataset()
            
            untouched_rar_files = []
            for rar_file in rar_files:
                course_name = extract_course_name(os.path.basename(rar_file))
                if course_name not in extracted_courses:
                    untouched_rar_files.append(rar_file)
            
            if untouched_rar_files:
                logging.info(f"[*] Found {len(untouched_rar_files)} untouched RAR files.")
                for rar_file in untouched_rar_files:
                    logging.info(f"    - {rar_file}")
                    await extract_and_upload_rar(rar_file)
                    await asyncio.sleep(5)  # Delay between files
            else:
                logging.info("[*] No untouched RAR files found, waiting...")
            
            # Wait 60 seconds before next scan
            await asyncio.sleep(60)
        except Exception as e:
            logging.error(f"[!] Worker error: {e}")
            await asyncio.sleep(60)

# === FastAPI Lifespan ===
@asynccontextmanager
async def lifespan(app: FastAPI):
    logging.info("πŸš€ Starting RAR Extractor FastAPI server...")
    task = asyncio.create_task(rar_processor_worker())
    yield
    task.cancel()
    logging.info("πŸ›‘ Shutting down RAR Extractor.")

# === Update App with Lifespan ===
app = FastAPI(lifespan=lifespan)

# === API Endpoints ===
@app.get("/")
def root():
    return {"status": "RAR Extractor running"}

@app.get("/health")
def health():
    return {"healthy": True}

@app.get("/scan")
def scan_rars():
    """Manually trigger RAR file scan and identify untouched ones"""
    rar_files = list_rar_files_in_dataset()
    extracted_courses = list_extracted_courses_in_dataset()
    
    untouched_rar_files = []
    for rar_file in rar_files:
        course_name = extract_course_name(os.path.basename(rar_file))
        if course_name not in extracted_courses:
            untouched_rar_files.append(rar_file)
            
    return {"total_rar_files": len(rar_files), "extracted_courses": len(extracted_courses), "untouched_rar_files": untouched_rar_files}

@app.post("/extract-all")
async def extract_all():
    """Manually trigger extraction of all untouched RAR files"""
    rar_files = list_rar_files_in_dataset()
    extracted_courses = list_extracted_courses_in_dataset()
    
    untouched_rar_files = []
    for rar_file in rar_files:
        course_name = extract_course_name(os.path.basename(rar_file))
        if course_name not in extracted_courses:
            untouched_rar_files.append(rar_file)

    if not untouched_rar_files:
        return {"message": "No untouched RAR files found to extract"}
    
    results = []
    for rar_file in untouched_rar_files:
        success = await extract_and_upload_rar(rar_file)
        results.append({"file": rar_file, "success": success})
        await asyncio.sleep(5)
    
    return {"processed": len(results), "results": results}