# api.py from flask import Flask, request, jsonify import os import zipfile import rarfile from PyPDF2 import PdfReader, PdfWriter from moviepy.editor import VideoFileClip from pydub import AudioSegment from PIL import Image import pdf2image app = Flask(__name__) def convert_file(input_path, output_path): if input_path.endswith('.pdf'): images = pdf2image.convert_from_path(input_path) for i, image in enumerate(images): image.save(f"{os.path.splitext(output_path)[0]}_page_{i+1}.webp", 'WEBP') webp_images = [Image.open(f"{os.path.splitext(output_path)[0]}_page_{i+1}.webp") for i in range(len(images))] webp_images[0].save(output_path, 'PDF', resolution=100.0, save_all=True, append_images=webp_images[1:]) elif input_path.endswith('.mp4'): video = VideoFileClip(input_path) video.write_videofile(output_path, codec='libx264') elif input_path.endswith('.wav'): audio = AudioSegment.from_wav(input_path) audio.export(output_path, format='mp3') elif input_path.endswith(('.png', '.jpg')): image = Image.open(input_path) image.save(output_path, 'WEBP') def extract_and_convert(file_path): if file_path.endswith('.zip'): with zipfile.ZipFile(file_path, 'r') as zip_ref: zip_ref.extractall(os.path.splitext(file_path)[0]) extracted_dir = os.path.splitext(file_path)[0] elif file_path.endswith('.rar'): with rarfile.RarFile(file_path, 'r') as rar_ref: rar_ref.extractall(os.path.splitext(file_path)[0]) extracted_dir = os.path.splitext(file_path)[0] else: return for root, _, files in os.walk(extracted_dir): for file in files: input_path = os.path.join(root, file) output_path = os.path.join(root, os.path.splitext(file)[0] + get_output_extension(file)) convert_file(input_path, output_path) def get_output_extension(file): if file.endswith('.pdf'): return '.pdf' elif file.endswith('.mp4'): return '.mkv' elif file.endswith('.wav'): return '.mp3' elif file.endswith(('.png', '.jpg')): return '.webp' return '' @app.route('/convert', methods=['POST']) def convert(): file = request.files['file'] file_path = f"temp_{file.filename}" file.save(file_path) extract_and_convert(file_path) return jsonify({"message": "Files converted successfully!"}) if __name__ == '__main__': app.run(debug=True)