Advertisement
Guest User

Deepseek - Python script to unpack and stream

a guest
Apr 30th, 2025
30
0
12 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.76 KB | Source Code | 0 0
  1. Deepseekv3
  2.  
  3. Prompt:
  4. I'm downloading a movie that's packaged in multiple rar files. As soon as the first rar file is downloaded, I want to start unpacking it so I can start watching immediately. For an uninterrupted experience, the contents of the remaining rar files should be streamed into the file I'm already watching.
  5.  
  6. The python script should run continuously to detect new rar files and stream their content into the existing file as they're downloaded
  7.  
  8. Response:
  9. Here's a Python script that monitors a directory for RAR files, starts unpacking as soon as the first part is available, and continuously appends content from subsequent parts to allow uninterrupted playback:
  10.  
  11. import os
  12. import time
  13. import patoolib
  14. import shutil
  15. from watchdog.observers import Observer
  16. from watchdog.events import FileSystemEventHandler
  17.  
  18. class RarHandler(FileSystemEventHandler):
  19.    def __init__(self, download_dir, output_file):
  20.        self.download_dir = download_dir
  21.        self.output_file = output_file
  22.        self.processed_files = set()
  23.        self.currently_processing = False
  24.        self.initial_extract_done = False
  25.        
  26.    def on_created(self, event):
  27.        if not event.is_directory and event.src_path.lower().endswith('.rar'):
  28.            self.process_rar(event.src_path)
  29.    
  30.    def on_modified(self, event):
  31.        if not event.is_directory and event.src_path.lower().endswith('.rar'):
  32.            self.process_rar(event.src_path)
  33.    
  34.    def process_rar(self, rar_path):
  35.        if rar_path in self.processed_files or self.currently_processing:
  36.            return
  37.            
  38.        self.currently_processing = True
  39.        try:
  40.            print(f"Processing new RAR file: {rar_path}")
  41.            
  42.            # Extract to temporary directory first
  43.            temp_dir = os.path.join(self.download_dir, "temp_extract")
  44.            os.makedirs(temp_dir, exist_ok=True)
  45.            
  46.            # Extract the RAR file
  47.            patoolib.extract_archive(rar_path, outdir=temp_dir)
  48.            
  49.            # Get extracted files (assuming single file extraction)
  50.            extracted_files = [f for f in os.listdir(temp_dir)
  51.                             if not f.startswith('.') and os.path.isfile(os.path.join(temp_dir, f))]
  52.            
  53.            if not extracted_files:
  54.                print(f"No files extracted from {rar_path}")
  55.                return
  56.                
  57.            # For the first RAR file, we move the content to output
  58.            if not self.initial_extract_done:
  59.                for file in extracted_files:
  60.                    src = os.path.join(temp_dir, file)
  61.                    shutil.move(src, self.output_file)
  62.                self.initial_extract_done = True
  63.                print(f"Initial extraction complete. Output file created at {self.output_file}")
  64.            else:
  65.                # For subsequent RARs, we append the content
  66.                for file in extracted_files:
  67.                    src = os.path.join(temp_dir, file)
  68.                    with open(src, 'rb') as fsrc, open(self.output_file, 'ab') as fdst:
  69.                        shutil.copyfileobj(fsrc, fdst)
  70.                    print(f"Appended content from {rar_path} to {self.output_file}")
  71.            
  72.            self.processed_files.add(rar_path)
  73.            
  74.        except Exception as e:
  75.            print(f"Error processing {rar_path}: {str(e)}")
  76.        finally:
  77.            # Clean up temp directory
  78.            if os.path.exists(temp_dir):
  79.                shutil.rmtree(temp_dir)
  80.            self.currently_processing = False
  81.  
  82. def monitor_and_extract(download_dir, output_file):
  83.    if not os.path.exists(download_dir):
  84.        raise FileNotFoundError(f"Download directory {download_dir} does not exist")
  85.    
  86.    event_handler = RarHandler(download_dir, output_file)
  87.    observer = Observer()
  88.    observer.schedule(event_handler, download_dir, recursive=False)
  89.    observer.start()
  90.    
  91.    print(f"Monitoring {download_dir} for RAR files. Output will be written to {output_file}")
  92.    
  93.    try:
  94.        while True:
  95.            time.sleep(1)
  96.    except KeyboardInterrupt:
  97.        observer.stop()
  98.    observer.join()
  99.  
  100. if __name__ == "__main__":
  101.    import argparse
  102.    
  103.    parser = argparse.ArgumentParser(description='Continuous RAR file extractor and streamer')
  104.    parser.add_argument('download_dir', help='Directory to monitor for RAR files')
  105.    parser.add_argument('output_file', help='Path to the output file where content will be streamed')
  106.    
  107.    args = parser.parse_args()
  108.    
  109.    monitor_and_extract(args.download_dir, args.output_file)
  110.  
  111.  
  112. Requirements
  113.  
  114.    Install the required packages:
  115. pip install patool watchdog
  116.  
  117.    You'll also need unrar installed on your system:
  118.  
  119.         On Linux: sudo apt-get install unrar
  120.  
  121.         On macOS: brew install unrar
  122.  
  123.         On Windows: Download from RARLab
  124.  
  125. How It Works
  126.  
  127.     The script monitors a directory for new or modified RAR files using watchdog.
  128.  
  129.     When the first RAR file appears, it extracts the content to your specified output file.
  130.  
  131.     As subsequent RAR files are downloaded, it extracts their content and appends it to the same output file.
  132.  
  133.     This allows media players to continue playing the file as new content is appended.
  134.  
  135. Usage
  136.  
  137. python rar_streamer.py /path/to/download/directory /path/to/output/file.mkv
  138.  
  139. Notes
  140.  
  141.     This assumes all RAR files contain parts of a single continuous file (common for movie downloads).
  142.  
  143.     The script handles one RAR file at a time to avoid conflicts.
  144.  
  145.     Temporary extraction files are cleaned up after processing.
  146.  
  147.     For best results, use a media player that can handle growing files (like VLC).
  148.  
  149.     If the RAR files are password protected, you'll need to modify the script to handle that case.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement