attendantelectro commited on
Commit
0ad7c19
·
verified ·
1 Parent(s): d19e9dc

Upload 3 files

Browse files
Files changed (3) hide show
  1. api.py +69 -0
  2. app.py +121 -0
  3. space.yaml +26 -0
api.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api.py
2
+ from flask import Flask, request, jsonify
3
+ import os
4
+ import zipfile
5
+ import rarfile
6
+ from PyPDF2 import PdfReader, PdfWriter
7
+ from moviepy.editor import VideoFileClip
8
+ from pydub import AudioSegment
9
+ from PIL import Image
10
+ import pdf2image
11
+
12
+ app = Flask(__name__)
13
+
14
+ def convert_file(input_path, output_path):
15
+ if input_path.endswith('.pdf'):
16
+ images = pdf2image.convert_from_path(input_path)
17
+ for i, image in enumerate(images):
18
+ image.save(f"{os.path.splitext(output_path)[0]}_page_{i+1}.webp", 'WEBP')
19
+ webp_images = [Image.open(f"{os.path.splitext(output_path)[0]}_page_{i+1}.webp") for i in range(len(images))]
20
+ webp_images[0].save(output_path, 'PDF', resolution=100.0, save_all=True, append_images=webp_images[1:])
21
+ elif input_path.endswith('.mp4'):
22
+ video = VideoFileClip(input_path)
23
+ video.write_videofile(output_path, codec='libx264')
24
+ elif input_path.endswith('.wav'):
25
+ audio = AudioSegment.from_wav(input_path)
26
+ audio.export(output_path, format='mp3')
27
+ elif input_path.endswith(('.png', '.jpg')):
28
+ image = Image.open(input_path)
29
+ image.save(output_path, 'WEBP')
30
+
31
+ def extract_and_convert(file_path):
32
+ if file_path.endswith('.zip'):
33
+ with zipfile.ZipFile(file_path, 'r') as zip_ref:
34
+ zip_ref.extractall(os.path.splitext(file_path)[0])
35
+ extracted_dir = os.path.splitext(file_path)[0]
36
+ elif file_path.endswith('.rar'):
37
+ with rarfile.RarFile(file_path, 'r') as rar_ref:
38
+ rar_ref.extractall(os.path.splitext(file_path)[0])
39
+ extracted_dir = os.path.splitext(file_path)[0]
40
+ else:
41
+ return
42
+
43
+ for root, _, files in os.walk(extracted_dir):
44
+ for file in files:
45
+ input_path = os.path.join(root, file)
46
+ output_path = os.path.join(root, os.path.splitext(file)[0] + get_output_extension(file))
47
+ convert_file(input_path, output_path)
48
+
49
+ def get_output_extension(file):
50
+ if file.endswith('.pdf'):
51
+ return '.pdf'
52
+ elif file.endswith('.mp4'):
53
+ return '.mkv'
54
+ elif file.endswith('.wav'):
55
+ return '.mp3'
56
+ elif file.endswith(('.png', '.jpg')):
57
+ return '.webp'
58
+ return ''
59
+
60
+ @app.route('/convert', methods=['POST'])
61
+ def convert():
62
+ file = request.files['file']
63
+ file_path = f"temp_{file.filename}"
64
+ file.save(file_path)
65
+ extract_and_convert(file_path)
66
+ return jsonify({"message": "Files converted successfully!"})
67
+
68
+ if __name__ == '__main__':
69
+ app.run(debug=True)
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import os
3
+ import zipfile
4
+ import rarfile
5
+ from PyPDF2 import PdfReader, PdfWriter
6
+ from moviepy.editor import VideoFileClip
7
+ from pydub import AudioSegment
8
+ from PIL import Image
9
+ import pdf2image
10
+ import streamlit as st
11
+
12
+ def convert_file(input_path, output_path):
13
+ if input_path.endswith('.pdf'):
14
+ # Convert PDF to WEBP
15
+ images = pdf2image.convert_from_path(input_path)
16
+ for i, image in enumerate(images):
17
+ image.save(f"{os.path.splitext(output_path)[0]}_page_{i+1}.webp", 'WEBP')
18
+
19
+ # Convert WEBP back to PDF
20
+ webp_images = [Image.open(f"{os.path.splitext(output_path)[0]}_page_{i+1}.webp") for i in range(len(images))]
21
+ webp_images[0].save(output_path, 'PDF', resolution=100.0, save_all=True, append_images=webp_images[1:])
22
+
23
+ elif input_path.endswith('.mp4'):
24
+ # Convert MP4 to MKV
25
+ video = VideoFileClip(input_path)
26
+ video.write_videofile(output_path, codec='libx264')
27
+
28
+ elif input_path.endswith('.wav'):
29
+ # Convert WAV to MP3
30
+ audio = AudioSegment.from_wav(input_path)
31
+ audio.export(output_path, format='mp3')
32
+
33
+ elif input_path.endswith(('.png', '.jpg')):
34
+ # Convert PNG/JPG to WEBP
35
+ image = Image.open(input_path)
36
+ image.save(output_path, 'WEBP')
37
+
38
+ def extract_and_convert(file_path):
39
+ if file_path.endswith('.zip'):
40
+ with zipfile.ZipFile(file_path, 'r') as zip_ref:
41
+ zip_ref.extractall(os.path.splitext(file_path)[0])
42
+ extracted_dir = os.path.splitext(file_path)[0]
43
+ elif file_path.endswith('.rar'):
44
+ with rarfile.RarFile(file_path, 'r') as rar_ref:
45
+ rar_ref.extractall(os.path.splitext(file_path)[0])
46
+ extracted_dir = os.path.splitext(file_path)[0]
47
+ else:
48
+ return
49
+
50
+ for root, _, files in os.walk(extracted_dir):
51
+ for file in files:
52
+ input_path = os.path.join(root, file)
53
+ output_path = os.path.join(root, os.path.splitext(file)[0] + get_output_extension(file))
54
+ convert_file(input_path, output_path)
55
+
56
+ def get_output_extension(file):
57
+ if file.endswith('.pdf'):
58
+ return '.pdf'
59
+ elif file.endswith('.mp4'):
60
+ return '.mkv'
61
+ elif file.endswith('.wav'):
62
+ return '.mp3'
63
+ elif file.endswith(('.png', '.jpg')):
64
+ return '.webp'
65
+ return ''
66
+
67
+ # Streamlit UI
68
+ st.title("File Converter Space")
69
+
70
+ # Language selection
71
+ language = st.selectbox("Select Language / انتخاب زبان", ["English", "فارسی"])
72
+
73
+ if language == "English":
74
+ description = """
75
+ This space allows you to convert files between various formats.
76
+ Supported conversions:
77
+ - PDF to WEBP and back to PDF
78
+ - MP4 to MKV
79
+ - WAV to MP3
80
+ - PNG/JPG to WEBP
81
+ """
82
+ upload_label = "Choose a file"
83
+ convert_button = "Convert Files"
84
+ success_message = "Files converted successfully!"
85
+ converted_files_label = "Converted Files:"
86
+ else:
87
+ description = """
88
+ این اسپیس به شما امکان می‌دهد فایل‌ها را بین فرمت‌های مختلف تبدیل کنید.
89
+ تبدیل‌های پشتیبانی شده:
90
+ - PDF به WEBP و بازگشت به PDF
91
+ - MP4 به MKV
92
+ - WAV به MP3
93
+ - PNG/JPG به WEBP
94
+ """
95
+ upload_label = "یک فایل انتخاب کنید"
96
+ convert_button = "تبدیل فایل‌ها"
97
+ success_message = "فایل‌ها با موفقیت تبدیل شدند!"
98
+ converted_files_label = "فایل‌های تبدیل شده:"
99
+
100
+ st.write(description)
101
+
102
+ uploaded_file = st.file_uploader(upload_label, type=['zip', 'rar'])
103
+
104
+ if uploaded_file is not None:
105
+ file_path = f"temp_{uploaded_file.name}"
106
+ with open(file_path, "wb") as f:
107
+ f.write(uploaded_file.getbuffer())
108
+
109
+ st.success("File uploaded successfully!")
110
+
111
+ if st.button(convert_button):
112
+ extract_and_convert(file_path)
113
+ st.success(success_message)
114
+
115
+ # Display converted files
116
+ st.write(converted_files_label)
117
+ extracted_dir = os.path.splitext(file_path)[0]
118
+ for root, _, files in os.walk(extracted_dir):
119
+ for file in files:
120
+ if file.endswith(('.pdf', '.mkv', '.mp3', '.webp')):
121
+ st.write(f"- {file}")
space.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # space.yaml
2
+ name: file-converter
3
+ description: A space to convert files using various Python libraries.
4
+
5
+ # Define the base image
6
+ base: python:3.9-slim
7
+
8
+ # Install system dependencies
9
+ install:
10
+ - apt-get update
11
+ - apt-get install -y ffmpeg
12
+
13
+ # Install Python dependencies
14
+ pip:
15
+ - zipfile36
16
+ - rarfile
17
+ - PyPDF2
18
+ - moviepy
19
+ - pydub
20
+ - Pillow
21
+ - pdf2image
22
+ - streamlit
23
+ - flask
24
+
25
+ # Define the main script to run
26
+ entrypoint: streamlit run /path/to/your/app.py