Spaces:
Runtime error
Runtime error
Delete api.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# api.pyfrom flask import Flask, request, jsonifyimport osimport zipfileimport rarfilefrom PyPDF2 import PdfReader, PdfWriterfrom moviepy.editor import VideoFileClipfrom pydub import AudioSegmentfrom PIL import Imageimport 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)api.pyDeleted-69