Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456784 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011140 unmodified lines1521531541551561571581591601611622 unmodified lines165166167168169170171import osimport zipfileimport tempfileimport shutilimport rarfileimport requestsfrom threading import Threadfrom flask import Flask, request, send_file4 unmodified linesfrom pydub import AudioSegmentimport streamlit as st# Fix werkzeug compatibilityfrom werkzeug.urls import url_quote# Flask API Setupapp = Flask(__name__)ALLOWED_EXTENSIONS = {'zip', 'rar', 'pdf', 'wav', 'mp4', 'jpg', 'png', 'jpeg'}def allowed_file(filename):# Check if the filename contains a dot and the extension is in ALLOWED_EXTENSIONSreturn '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSdef convert_single_file(input_path):base_name = os.path.splitext(input_path)[0]if input_path.endswith('.pdf'):images = convert_from_path(input_path)output_path = f"{base_name}_converted.pdf"webp_images = []for i, image in enumerate(images):webp_path = f"{base_name}_page_{i+1}.webp"image.save(webp_path, 'WEBP')webp_images.append(Image.open(webp_path))webp_images[0].save(output_path, 'PDF', save_all=True, append_images=webp_images[1:])return output_pathelif input_path.endswith('.mp4'):output_path = f"{base_name}.mkv"VideoFileClip(input_path).write_videofile(output_path, codec='libx264')return output_pathelif input_path.endswith('.wav'):output_path = f"{base_name}.mp3"AudioSegment.from_wav(input_path).export(output_path, format='mp3')return output_pathelif input_path.lower().endswith(('.png', '.jpg', '.jpeg')):output_path = f"{base_name}.webp"Image.open(input_path).save(output_path, 'WEBP')return output_pathreturn input_path@app.route('/convert', methods=['POST'])def handle_conversion():if 'file' not in request.files:return {"error": "No file uploaded"}, 400file = request.files['file']if not file or file.filename == '':return {"error": "Empty filename"}, 400if not allowed_file(file.filename):return {"error": "Unsupported file type"}, 400try:with tempfile.TemporaryDirectory() as temp_dir:filename = secure_filename(file.filename)upload_path = os.path.join(temp_dir, filename)file.save(upload_path)# Single File Conversionif filename.split('.')[-1].lower() in {'pdf','wav','mp4','jpg','png','jpeg'}:converted_path = convert_single_file(upload_path)return send_file(converted_path, as_attachment=True)# Archive Processingif filename.endswith('.zip'):with zipfile.ZipFile(upload_path, 'r') as z:z.extractall(temp_dir)else:with rarfile.RarFile(upload_path, 'r') as r:r.extractall(temp_dir)# Convert filesfor root, _, files in os.walk(temp_dir):for f in files:if f != filename:convert_single_file(os.path.join(root, f))# Create output zipoutput_path = os.path.join(temp_dir, "converted.zip")with zipfile.ZipFile(output_path, 'w') as z:for root, _, files in os.walk(temp_dir):for f in files:if f != filename:z.write(os.path.join(root, f), arcname=f)return send_file(output_path, as_attachment=True)except Exception as e:return {"error": f"Processing failed: {str(e)}"}, 500# Streamlit UIdef streamlit_app():40 unmodified lines)if response.status_code == 200:st.success(t["success"])st.download_button(label=t["download"],data=response.content,file_name="converted_files.zip" if 'zip' in response.headers.get('Content-Type','') else f"converted_{uploaded.name}",)else:st.error(f"Error {response.status_code}: {response.text}")2 unmodified linesst.error(f"Connection error: {str(e)}")if __name__ == '__main__':# Run Flask in background threadThread(target=lambda: app.run(host='0.0.0.0', port=7860, debug=False)).start()# Run Streamlitstreamlit_app()123454 unmodified lines101112131415161718192021222324252627282940 unmodified lines707172737475767778798081828384858687882 unmodified lines91929394959697import osimport subprocessimport requestsfrom threading import Threadfrom flask import Flask, request, send_file4 unmodified linesfrom pydub import AudioSegmentimport streamlit as st# Fix werkzeug compatibility for older versions if neededfrom werkzeug.urls import url_quote# Flask API Setup (برای اینجا فقط به هدف اجرا به عنوان پسزمینه استفاده میشود)app = Flask(__name__)ALLOWED_EXTENSIONS = {'zip', 'rar', 'pdf', 'wav', 'mp4', 'jpg', 'png', 'jpeg'}def allowed_file(filename):return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS# راهاندازی API به عنوان پردازش پسزمینهdef run_api():# اجرای فایل api.py به صورت subprocess.subprocess.run(['python', 'api.py'])# Streamlit UIdef streamlit_app():40 unmodified lines)if response.status_code == 200:# استخراج نام فایل خروجی از header Content-Dispositioncd = response.headers.get('Content-Disposition', '')filename = Noneif 'filename=' in cd:filename = cd.split("filename=")[1].strip().strip('"')else:filename = f"converted_{uploaded.name}"st.success(t["success"])st.download_button(label=t["download"],data=response.content,file_name=filename,)else:st.error(f"Error {response.status_code}: {response.text}")2 unmodified linesst.error(f"Connection error: {str(e)}")if __name__ == '__main__':# اجرای API داخل یک ترد پسزمینه (در صورتی که نیاز به اجرای همزمان داشته باشید)Thread(target=run_api, daemon=True).start()# اجرای رابط کاربری Streamlitstreamlit_app()
app.py+19-93