import os import time import sys import msvcrt import logging from datetime import datetime from ftplib import FTP import re from tqdm import tqdm # Configuration constants FTP_HOST = '89.117.8.184' FTP_USER = 'u127449946.bb' FTP_PASS = '@Panasonic291' FTP_DIR = '/' LOCAL_DIR = '.' FILENAME_PATTERN = r'\d{8}_\d{6}_[A-Za-z]+\.mp3' PRIORITY_CITIES = ['Karachi', 'Sialkot', 'Islamabad', 'Lahore', 'Bhawalpur', 'Peshawar'] MIN_FILE_SIZE = 1024 * 1024 # 1MB LOG_FILE = 'upload_log.txt' def setup_logging(): logging.basicConfig( filename=LOG_FILE, level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s' ) def wait_or_exit(seconds=10): print("\nPress Enter to exit manually or wait 10 seconds...") start_time = time.time() while True: if msvcrt.kbhit(): if msvcrt.getch() == b'\r': print("\n👋 Exiting by user input.") sys.exit(0) elapsed = time.time() - start_time if elapsed >= seconds: print(f"\n⏳ Time up. Exiting automatically.") sys.exit(0) remaining = seconds - int(elapsed) if remaining > 0: print(f"\r⏳ Exiting in {remaining} seconds...", end='') time.sleep(1) def upload_file_with_progress(ftp, file_path, remote_filename): def callback(data): pb.update(len(data)) file_size = os.path.getsize(file_path) with open(file_path, 'rb') as f: with tqdm(total=file_size, unit='B', unit_scale=True, desc=f"Uploading {remote_filename}") as pb: ftp.storbinary(f'STOR {remote_filename}', f, blocksize=8192, callback=callback) def main(): print("=== Starting Upload Script ===") setup_logging() try: # Connect to FTP try: ftp = FTP(FTP_HOST) ftp.login(FTP_USER, FTP_PASS) ftp.cwd(FTP_DIR) logging.info("FTP connection successful") print("✅ FTP connection successful") except Exception as e: logging.error(f"FTP connection failed: {str(e)}") print(f"❌ FTP connection failed: {str(e)}") wait_or_exit() return # Find today's file today = datetime.now().strftime('%Y%m%d') today_filename = None available_files = [] print(f"Scanning for files in: {LOCAL_DIR}") for file in os.listdir(LOCAL_DIR): if file.lower().endswith('.mp3') and re.match(FILENAME_PATTERN, file): full_path = os.path.join(LOCAL_DIR, file) if os.path.getsize(full_path) >= MIN_FILE_SIZE: available_files.append(file) if not available_files: logging.warning("No valid recording found for today.") print("❌ No valid recording found for today.") wait_or_exit() return # Select file based on priority cities candidates = [] for file in available_files: for city in PRIORITY_CITIES: if city.lower() in file.lower(): candidates.append((city, file)) break if candidates: # Sort by priority selected = sorted(candidates, key=lambda x: PRIORITY_CITIES.index(x[0]))[0][1] else: selected = available_files[0] print(f"✅ Selected file: {selected}") logging.info(f"Selected file: {selected}") # Prepare upload upload_name = f"{datetime.now().strftime('%Y-%m-%d')}.mp3" upload_path = os.path.join(LOCAL_DIR, selected) # Upload file try: upload_file_with_progress(ftp, upload_path, upload_name) logging.info("Upload completed") print("✅ Upload completed") except Exception as e: logging.error(f"Upload failed: {str(e)}") print(f"❌ Upload failed: {str(e)}") wait_or_exit() return # Clean old files (keep latest 2) try: remote_files = ftp.nlst() mp3_files = [f for f in remote_files if re.match(r'\d{4}-\d{2}-\d{2}\.mp3', f)] if len(mp3_files) > 2: print("🔍 Valid .mp3 files on FTP: " + ", ".join(mp3_files)) to_delete = sorted(mp3_files)[:-2] # Keep newest 2 for file in to_delete: try: ftp.delete(file) logging.info(f"Deleted old file: {file}") print(f"🗑 Deleted old file: {file}") except Exception as e: logging.warning(f"Could not delete {file}: {str(e)}") print(f"⚠️ Could not delete {file}: {str(e)}") else: logging.info("No old files to delete. Keeping the latest two.") print("📌 No old files to delete. Keeping the latest two.") except Exception as e: logging.warning(f"Error cleaning old files: {str(e)}") print(f"⚠️ Error cleaning old files: {str(e)}") ftp.quit() logging.info("Script finished") print("✅ Script finished") except Exception as e: logging.error(f"An unhandled error occurred: {str(e)}") print(f"❌ An unhandled error occurred: {str(e)}") wait_or_exit() if __name__ == "__main__": main()