File-Converter / app.py
attendantelectro's picture
Upload 2 files
c20726b verified
import os
import subprocess
import requests
from threading import Thread
from flask import Flask, request, send_file
from werkzeug.utils import secure_filename
from pdf2image import convert_from_path
from PIL import Image
from moviepy.editor import VideoFileClip
from pydub import AudioSegment
import streamlit as st
# Fix werkzeug compatibility for older versions if needed
from 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 UI
def streamlit_app():
st.set_page_config(page_title="File Converter", layout="wide")
TEXTS = {
"English": {
"title": "Universal File Converter",
"desc": "Convert files/archives (ZIP/RAR/PDF/WAV/MP4/IMG)",
"upload": "Upload File",
"error_type": "Unsupported file type!",
"success": "Conversion Successful!",
"download": "Download"
},
"فارسی": {
"title": "مبدل جهانی فایل",
"desc": "تبدیل فایل/آرشیو (ZIP/RAR/PDF/WAV/MP4/تصویر)",
"upload": "آپلود فایل",
"error_type": "نوع فایل پشتیبانی نمیشود!",
"success": "تبدیل با موفقیت انجام شد!",
"download": "دانلود"
}
}
lang = st.sidebar.selectbox("", ["English", "فارسی"])
t = TEXTS[lang]
st.title(t["title"])
st.markdown(f"**{t['desc']}**")
uploaded = st.file_uploader(t["upload"], type=ALLOWED_EXTENSIONS)
if uploaded:
file_extension = uploaded.name.split('.')[-1].lower()
if file_extension not in ALLOWED_EXTENSIONS:
st.error(t["error_type"])
elif st.button("Convert"):
try:
with st.spinner("Processing..."):
response = requests.post(
"http://localhost:7860/convert",
files={"file": (uploaded.name, uploaded.getvalue(), uploaded.type)},
timeout=300
)
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=filename,
)
else:
st.error(f"Error {response.status_code}: {response.text}")
except Exception as e:
st.error(f"Connection error: {str(e)}")
if __name__ == '__main__':
# اجرای API داخل یک ترد پس‌زمینه (در صورتی که نیاز به اجرای همزمان داشته باشید)
Thread(target=run_api, daemon=True).start()
# اجرای رابط کاربری Streamlit
streamlit_app()