attendantelectro commited on
Commit
2281157
·
verified ·
1 Parent(s): ddb5f9f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -87
app.py CHANGED
@@ -1,97 +1,67 @@
 
1
  import os
2
- import subprocess
3
- import requests
4
- from threading import Thread
5
- from flask import Flask, request, send_file
6
  from werkzeug.utils import secure_filename
7
- from pdf2image import convert_from_path
8
- from PIL import Image
9
- from moviepy.editor import VideoFileClip
10
- from pydub import AudioSegment
11
  import streamlit as st
 
12
 
13
- # Fix werkzeug compatibility for older versions if needed
14
- from werkzeug.urls import url_quote
15
 
16
- # Flask API Setup (برای اینجا فقط به هدف اجرا به عنوان پس‌زمینه استفاده می‌شود)
17
- app = Flask(__name__)
18
- ALLOWED_EXTENSIONS = {'zip', 'rar', 'pdf', 'wav', 'mp4', 'jpg', 'png', 'jpeg'}
19
-
20
- def allowed_file(filename):
21
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
22
-
23
- # راه‌اندازی API به عنوان پردازش پس‌زمینه
24
- def run_api():
25
- # اجرای فایل api.py به صورت subprocess.
26
- subprocess.run(['python', 'api.py'])
27
-
28
- # Streamlit UI
29
- def streamlit_app():
30
- st.set_page_config(page_title="File Converter", layout="wide")
31
-
32
- TEXTS = {
33
- "English": {
34
- "title": "File Converter",
35
- "desc": "Convert files/archives (ZIP/RAR/PDF/WAV/MP4/IMG)",
36
- "upload": "Upload File",
37
- "error_type": "Unsupported file type!",
38
- "success": "Conversion Successful!",
39
- "download": "Download"
40
- },
41
- "فارسی": {
42
- "title": "مبدل فایل",
43
- "desc": "تبدیل فایل/آرشیو (ZIP/RAR/PDF/WAV/MP4/تصویر)",
44
- "upload": "آپلود فایل",
45
- "error_type": "نوع فایل پشتیبانی نمیشود!",
46
- "success": "تبدیل با موفقیت انجام شد!",
47
- "download": "دانلود"
48
- }
49
  }
 
50
 
51
- lang = st.sidebar.selectbox("", ["English", "فارسی"])
52
- t = TEXTS[lang]
 
53
 
54
- st.title(t["title"])
55
- st.markdown(f"**{t['desc']}**")
56
 
57
- uploaded = st.file_uploader(t["upload"], type=ALLOWED_EXTENSIONS)
58
-
59
- if uploaded:
60
- file_extension = uploaded.name.split('.')[-1].lower()
61
- if file_extension not in ALLOWED_EXTENSIONS:
62
- st.error(t["error_type"])
63
- elif st.button("Convert"):
64
- try:
65
- with st.spinner("Processing..."):
66
- response = requests.post(
67
- "http://localhost:7860/convert",
68
- files={"file": (uploaded.name, uploaded.getvalue(), uploaded.type)},
69
- timeout=300
70
- )
71
-
72
- if response.status_code == 200:
73
- # استخراج نام فایل خروجی از header Content-Disposition
74
- cd = response.headers.get('Content-Disposition', '')
75
- filename = None
76
- if 'filename=' in cd:
77
- filename = cd.split("filename=")[1].strip().strip('"')
78
- else:
79
- filename = f"converted_{uploaded.name}"
80
-
81
- st.success(t["success"])
82
- st.download_button(
83
- label=t["download"],
84
- data=response.content,
85
- file_name=filename,
86
- )
87
  else:
88
- st.error(f"Error {response.status_code}: {response.text}")
89
-
90
- except Exception as e:
91
- st.error(f"Connection error: {str(e)}")
92
-
93
- if __name__ == '__main__':
94
- # اجرای API داخل یک ترد پس‌زمینه (در صورتی که نیاز به اجرای همزمان داشته باشید)
95
- Thread(target=run_api, daemon=True).start()
96
- # اجرای رابط کاربری Streamlit
97
- streamlit_app()
 
1
+ # app.py
2
  import os
3
+ import io
4
+ import zipfile
5
+ tempfile = __import__('tempfile')
 
6
  from werkzeug.utils import secure_filename
 
 
 
 
7
  import streamlit as st
8
+ from api import ALLOWED_EXTENSIONS, allowed_file, convert_path
9
 
10
+ # Streamlit page configuration
11
+ st.set_page_config(page_title="Universal File Converter", layout="wide")
12
 
13
+ # Multilingual interface text\TEXTS = {
14
+ "English": {
15
+ "title": "Universal File Converter",
16
+ "desc": "Convert files or archives (ZIP, RAR, PDF, WAV, MP4, Images)",
17
+ "upload": "Upload File",
18
+ "convert_btn": "Convert",
19
+ "processing": "Processing...",
20
+ "error_type": "Unsupported file type!",
21
+ "success": "Conversion successful!",
22
+ "download": "Download"
23
+ },
24
+ "فارسی": {
25
+ "title": "مبدل جهانی فایل",
26
+ "desc": "تبدیل فایل یا آرشیو (ZIP, RAR, PDF, WAV, MP4, تصاویر)",
27
+ "upload": "آپلود فایل",
28
+ "convert_btn": "تبدیل",
29
+ "processing": "در حال پردازش...",
30
+ "error_type": "نوع فایل پشتیبانی نمیشود!",
31
+ "success": "تبدیل با موفقیت انجام شد!",
32
+ "download": "دانلود"
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  }
34
+ }
35
 
36
+ # Language selection
37
+ lang = st.sidebar.selectbox("", list(TEXTS.keys()))
38
+ T = TEXTS[lang]
39
 
40
+ st.title(T['title'])
41
+ st.markdown(f"**{T['desc']}**")
42
 
43
+ uploaded = st.file_uploader(T['upload'], type=list(ALLOWED_EXTENSIONS))
44
+ if uploaded:
45
+ fname = secure_filename(uploaded.name)
46
+ if not allowed_file(fname):
47
+ st.error(T['error_type'])
48
+ elif st.button(T['convert_btn']):
49
+ with st.spinner(T['processing']):
50
+ with tempfile.TemporaryDirectory() as tmpdir:
51
+ in_path = os.path.join(tmpdir, fname)
52
+ with open(in_path, 'wb') as f:
53
+ f.write(uploaded.getbuffer())
54
+ converted = convert_path(in_path, tmpdir)
55
+ if len(converted) == 1:
56
+ out_path = converted[0]
57
+ with open(out_path, 'rb') as f:
58
+ data = f.read()
59
+ st.success(T['success'])
60
+ st.download_button(T['download'], data, os.path.basename(out_path))
 
 
 
 
 
 
 
 
 
 
 
 
61
  else:
62
+ zip_buffer = io.BytesIO()
63
+ with zipfile.ZipFile(zip_buffer, 'w') as zf:
64
+ for p in converted:
65
+ zf.write(p, arcname=os.path.basename(p))
66
+ st.success(T['success'])
67
+ st.download_button(T['download'], zip_buffer.getvalue(), 'converted_files.zip')