Spaces:
Runtime error
Runtime error
Update api.py
Browse files
api.py
CHANGED
|
@@ -1,126 +1,96 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import zipfile
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
output_path = f"{base_name}.webp"
|
| 51 |
-
Image.open(input_path).save(output_path, 'WEBP')
|
| 52 |
-
return output_path
|
| 53 |
-
|
| 54 |
-
# در صورت نداشتن تغییر، همان مسیر بازگردانده میشود.
|
| 55 |
return input_path
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
# ایجاد فایل آرشیو خروجی
|
| 103 |
-
output_path = os.path.join(temp_dir, "converted.zip")
|
| 104 |
-
with zipfile.ZipFile(output_path, 'w') as z:
|
| 105 |
-
for root, _, files in os.walk(temp_dir):
|
| 106 |
-
for f in files:
|
| 107 |
-
if f != filename:
|
| 108 |
-
full_path = os.path.join(root, f)
|
| 109 |
-
z.write(full_path, arcname=f)
|
| 110 |
-
|
| 111 |
-
return send_file(
|
| 112 |
-
output_path,
|
| 113 |
-
as_attachment=True,
|
| 114 |
-
download_name="converted_files.zip"
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
except Exception as e:
|
| 118 |
-
return {"error": f"Processing failed: {str(e)}"}, 500
|
| 119 |
-
finally:
|
| 120 |
-
try:
|
| 121 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 122 |
-
except Exception:
|
| 123 |
-
pass
|
| 124 |
-
|
| 125 |
-
if __name__ == '__main__':
|
| 126 |
-
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
+
#api.py
|
| 2 |
+
|
| 3 |
+
import os import zipfile tempfile = import('tempfile') import shutil import rarfile from pdf2image import convert_from_path from PIL import Image from moviepy.editor import VideoFileClip from pydub import AudioSegment
|
| 4 |
+
|
| 5 |
+
Allowed extensions for conversion
|
| 6 |
+
|
| 7 |
+
ALLOWED_EXTENSIONS = {'zip', 'rar', 'pdf', 'wav', 'mp4', 'jpg', 'jpeg', 'png'}
|
| 8 |
+
|
| 9 |
+
def allowed_file(filename): """Check if the file extension is allowed.""" return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 10 |
+
|
| 11 |
+
def convert_single_file(input_path, output_dir=None): """ Convert a single file based on its extension. Returns the path to the converted file. """ base, ext = os.path.splitext(os.path.basename(input_path)) if output_dir is None: output_dir = os.path.dirname(input_path) ext = ext.lower()
|
| 12 |
+
|
| 13 |
+
if ext == '.pdf':
|
| 14 |
+
images = convert_from_path(input_path)
|
| 15 |
+
out_pdf = os.path.join(output_dir, f"{base}_converted.pdf")
|
| 16 |
+
webp_imgs = []
|
| 17 |
+
for i, img in enumerate(images, start=1):
|
| 18 |
+
webp_path = os.path.join(output_dir, f"{base}_page_{i}.webp")
|
| 19 |
+
img.save(webp_path, 'WEBP')
|
| 20 |
+
webp_imgs.append(Image.open(webp_path))
|
| 21 |
+
# Save all pages back to PDF
|
| 22 |
+
webp_imgs[0].save(out_pdf, 'PDF', save_all=True, append_images=webp_imgs[1:])
|
| 23 |
+
# Cleanup temporary WEBP files
|
| 24 |
+
for img in webp_imgs:
|
| 25 |
+
img.close()
|
| 26 |
+
for i in range(1, len(images)+1):
|
| 27 |
+
os.remove(os.path.join(output_dir, f"{base}_page_{i}.webp"))
|
| 28 |
+
return out_pdf
|
| 29 |
+
|
| 30 |
+
elif ext == '.mp4':
|
| 31 |
+
out_vid = os.path.join(output_dir, f"{base}.mkv")
|
| 32 |
+
clip = VideoFileClip(input_path)
|
| 33 |
+
clip.write_videofile(out_vid, codec='libx264', audio_codec='aac')
|
| 34 |
+
clip.reader.close()
|
| 35 |
+
clip.audio.reader.close_proc()
|
| 36 |
+
return out_vid
|
| 37 |
+
|
| 38 |
+
elif ext == '.wav':
|
| 39 |
+
out_audio = os.path.join(output_dir, f"{base}.mp3")
|
| 40 |
+
AudioSegment.from_wav(input_path).export(out_audio, format='mp3')
|
| 41 |
+
return out_audio
|
| 42 |
+
|
| 43 |
+
elif ext in {'.png', '.jpg', '.jpeg'}:
|
| 44 |
+
out_img = os.path.join(output_dir, f"{base}.webp")
|
| 45 |
+
Image.open(input_path).save(out_img, 'WEBP')
|
| 46 |
+
return out_img
|
| 47 |
+
|
| 48 |
+
else:
|
| 49 |
+
# No conversion needed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return input_path
|
| 51 |
|
| 52 |
+
def extract_archive(input_path, extract_to): """Extract ZIP or RAR archives.""" if input_path.lower().endswith('.zip'): with zipfile.ZipFile(input_path, 'r') as z: z.extractall(extract_to) else: with rarfile.RarFile(input_path, 'r') as r: r.extractall(extract_to)
|
| 53 |
+
|
| 54 |
+
def convert_path(input_path, work_dir): """ Convert a file or archive in work_dir. Returns a list of converted file paths. """ ext = os.path.splitext(input_path)[1].lower().lstrip('.') outputs = [] if ext in {'zip', 'rar'}: extract_dir = os.path.join(work_dir, 'extracted') os.makedirs(extract_dir, exist_ok=True) extract_archive(input_path, extract_dir) # Convert each extracted file for root, _, files in os.walk(extract_dir): for fname in files: fpath = os.path.join(root, fname) if allowed_file(fname): outputs.append(convert_single_file(fpath, work_dir)) else: outputs.append(convert_single_file(input_path, work_dir)) return outputs
|
| 55 |
+
|
| 56 |
+
app.py
|
| 57 |
+
|
| 58 |
+
import os import io import zipfile tempfile = import('tempfile') from werkzeug.utils import secure_filename import streamlit as st from api import ALLOWED_EXTENSIONS, allowed_file, convert_path
|
| 59 |
+
|
| 60 |
+
Streamlit page configuration
|
| 61 |
+
|
| 62 |
+
st.set_page_config(page_title="Universal File Converter", layout="wide")
|
| 63 |
+
|
| 64 |
+
Multilingual interface text\TEXTS = {
|
| 65 |
+
|
| 66 |
+
"English": {
|
| 67 |
+
"title": "Universal File Converter",
|
| 68 |
+
"desc": "Convert files or archives (ZIP, RAR, PDF, WAV, MP4, Images)",
|
| 69 |
+
"upload": "Upload File",
|
| 70 |
+
"convert_btn": "Convert",
|
| 71 |
+
"processing": "Processing...",
|
| 72 |
+
"error_type": "Unsupported file type!",
|
| 73 |
+
"success": "Conversion successful!",
|
| 74 |
+
"download": "Download"
|
| 75 |
+
},
|
| 76 |
+
"فارسی": {
|
| 77 |
+
"title": "مبدل جهانی فایل",
|
| 78 |
+
"desc": "تبدیل فایل یا آرشیو (ZIP, RAR, PDF, WAV, MP4, تصاویر)",
|
| 79 |
+
"upload": "آپلود فایل",
|
| 80 |
+
"convert_btn": "تبدیل",
|
| 81 |
+
"processing": "در حال پردازش...",
|
| 82 |
+
"error_type": "نوع فایل پشتیبانی نمیشود!",
|
| 83 |
+
"success": "تبدیل با موفقیت انجام شد!",
|
| 84 |
+
"download": "دانلود"
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
Language selection
|
| 90 |
+
|
| 91 |
+
lang = st.sidebar.selectbox("", list(TEXTS.keys())) T = TEXTS[lang]
|
| 92 |
+
|
| 93 |
+
st.title(T['title']) st.markdown(f"{T['desc']}")
|
| 94 |
+
|
| 95 |
+
uploaded = st.file_uploader(T['upload'], type=list(ALLOWED_EXTENSIONS)) if uploaded: fname = secure_filename(uploaded.name) if not allowed_file(fname): st.error(T['error_type']) elif st.button(T['convert_btn']): with st.spinner(T['processing']): with tempfile.TemporaryDirectory() as tmpdir: in_path = os.path.join(tmpdir, fname) with open(in_path, 'wb') as f: f.write(uploaded.getbuffer()) converted = convert_path(in_path, tmpdir) if len(converted) == 1: out_path = converted[0] with open(out_path, 'rb') as f: data = f.read() st.success(T['success']) st.download_button(T['download'], data, os.path.basename(out_path)) else: zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w') as zf: for p in converted: zf.write(p, arcname=os.path.basename(p)) st.success(T['success']) st.download_button(T['download'], zip_buffer.getvalue(), 'converted_files.zip')
|
| 96 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|