Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234523454 unmodified lines10111216131415191617181920242122272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071082324252627282940 unmodified lines707172737475767778798081828384159858687882 unmodified lines91929316816917094959697import osimport zipfileimport tempfileimport shutilimport rarfileimport subprocessimport requestsfrom threading import Threadfrom flask import Flask, request, send_file4 unmodified linesfrom pydub import AudioSegmentimport streamlit as st
# Fix werkzeug compatibility# Fix werkzeug compatibility for older versions if neededfrom werkzeug.urls import url_quote
# Flask API Setup# Flask API Setup (برای اینجا فقط به هدف اجرا به عنوان پسزمینه استفاده میشود)app = 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_EXTENSIONS return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def 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_path
elif input_path.endswith('.mp4'): output_path = f"{base_name}.mkv" VideoFileClip(input_path).write_videofile(output_path, codec='libx264') return output_path
elif input_path.endswith('.wav'): output_path = f"{base_name}.mp3" AudioSegment.from_wav(input_path).export(output_path, format='mp3') return output_path
elif input_path.lower().endswith(('.png', '.jpg', '.jpeg')): output_path = f"{base_name}.webp" Image.open(input_path).save(output_path, 'WEBP') return output_path
return input_path
@app.route('/convert', methods=['POST'])def handle_conversion(): if 'file' not in request.files: return {"error": "No file uploaded"}, 400
file = request.files['file'] if not file or file.filename == '': return {"error": "Empty filename"}, 400
if not allowed_file(file.filename): return {"error": "Unsupported file type"}, 400
try: 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 Conversion if 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 Processing if 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 files for root, _, files in os.walk(temp_dir): for f in files: if f != filename: convert_single_file(os.path.join(root, f))
# Create output zip output_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# راهاندازی 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-Disposition cd = response.headers.get('Content-Disposition', '') filename = None if '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="converted_files.zip" if 'zip' in response.headers.get('Content-Type','') else f"converted_{uploaded.name}", file_name=filename, ) else: st.error(f"Error {response.status_code}: {response.text}")2 unmodified lines st.error(f"Connection error: {str(e)}")
if __name__ == '__main__': # Run Flask in background thread Thread(target=lambda: app.run(host='0.0.0.0', port=7860, debug=False)).start() # Run Streamlit # اجرای API داخل یک ترد پسزمینه (در صورتی که نیاز به اجرای همزمان داشته باشید) Thread(target=run_api, daemon=True).start() # اجرای رابط کاربری Streamlit streamlit_app()app.py+19-93