ScriptDemon's picture
Update app.py
8924b1d verified
Raw
History Blame Contribute Delete
9.04 kB
import streamlit as st
from PIL import Image, ImageDraw
import img2pdf
from io import BytesIO
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import nbformat
from nbconvert import HTMLExporter
from weasyprint import HTML
import pandas as pd
import markdown
from gtts import gTTS
import speech_recognition as sr
import fitz # PyMuPDF
import os
st.title("Hari Files Converter")
# CSS for styling cards
st.markdown("""
<style>
.card {
background-color: #f9f9f9;
padding: 20px;
border-radius: 10px;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
.card-title {
font-size: 20px;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.card-button {
background-color: #007BFF;
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
text-align: center;
display: inline-block;
font-size: 16px;
font-weight: bold;
transition: background-color 0.3s ease;
}
.card-button:hover {
background-color: #0056b3;
}
</style>
""", unsafe_allow_html=True)
# Conversion functions
def image_to_pdf(uploaded_file):
image = Image.open(uploaded_file)
pdf_bytes = img2pdf.convert(image.filename, dpi=300)
return pdf_bytes
def docx_to_html(docx_path):
document = Document(docx_path)
html_content = "<html><body style='font-family: Arial, sans-serif; margin: 20px;'>"
for para in document.paragraphs:
style = para.style
font_size = Pt(12).pt if not (style.font and style.font.size) else style.font.size.pt
alignment = para.alignment or WD_PARAGRAPH_ALIGNMENT.LEFT
align = "left" if alignment == WD_PARAGRAPH_ALIGNMENT.LEFT else \
"center" if alignment == WD_PARAGRAPH_ALIGNMENT.CENTER else \
"right" if alignment == WD_PARAGRAPH_ALIGNMENT.RIGHT else "justify"
html_content += f"<p style='font-size: {font_size}px; text-align: {align};'>{para.text}</p>"
html_content += "</body></html>"
return html_content
def docx_to_pdf_func(uploaded_file):
temp_docx_path = "temp.docx"
with open(temp_docx_path, "wb") as f:
f.write(uploaded_file.getbuffer())
html_content = docx_to_html(temp_docx_path)
output_pdf = BytesIO()
HTML(string=html_content).write_pdf(output_pdf)
os.remove(temp_docx_path)
return output_pdf.getvalue()
def ipynb_to_pdf(uploaded_file):
notebook_content = uploaded_file.read().decode('utf-8')
notebook = nbformat.reads(notebook_content, as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_name = 'classic'
html_data, _ = html_exporter.from_notebook_node(notebook)
output_pdf = BytesIO()
HTML(string=html_data).write_pdf(output_pdf)
return output_pdf.getvalue()
def docx_to_image(uploaded_file):
document = Document(uploaded_file)
text = "\n".join([para.text for para in document.paragraphs])
image = Image.new('RGB', (1600, 1200), color=(255, 255, 255))
d = ImageDraw.Draw(image)
d.text((10, 10), text, fill=(0, 0, 0))
output_image = BytesIO()
image.save(output_image, format="PNG", dpi=(300, 300))
return output_image.getvalue()
def image_to_docx(uploaded_file):
document = Document()
image = Image.open(uploaded_file)
max_width = Inches(6)
width, height = image.size
aspect_ratio = height / width
document.add_picture(uploaded_file, width=max_width, height=max_width * aspect_ratio)
output_docx = BytesIO()
document.save(output_docx)
return output_docx.getvalue()
def pdf_to_image(uploaded_file):
pdf_document = fitz.open(stream=uploaded_file.read(), filetype="pdf")
image_buffers = []
for page_number in range(len(pdf_document)):
page = pdf_document.load_page(page_number)
pix = page.get_pixmap()
img_buffer = BytesIO()
pix.save(img_buffer)
image_buffers.append(img_buffer.getvalue())
return image_buffers
def text_to_pdf(uploaded_file):
text = uploaded_file.read().decode("utf-8")
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, text)
output_pdf = BytesIO()
pdf.output(output_pdf)
return output_pdf.getvalue()
def markdown_to_pdf(uploaded_file):
markdown_text = uploaded_file.read().decode("utf-8")
html_content = markdown.markdown(markdown_text)
output_pdf = BytesIO()
HTML(string=html_content).write_pdf(output_pdf)
return output_pdf.getvalue()
def html_to_image(uploaded_file):
html_content = uploaded_file.read().decode("utf-8")
output_image = BytesIO()
HTML(string=html_content).write_png(output_image)
return output_image.getvalue()
def csv_to_excel(uploaded_file):
df = pd.read_csv(uploaded_file)
output_excel = BytesIO()
df.to_excel(output_excel, index=False, engine='openpyxl')
return output_excel.getvalue()
def excel_to_csv(uploaded_file):
df = pd.read_excel(uploaded_file)
output_csv = BytesIO()
df.to_csv(output_csv, index=False)
return output_csv.getvalue()
def audio_to_text(uploaded_file):
recognizer = sr.Recognizer()
with sr.AudioFile(uploaded_file) as source:
audio_data = recognizer.record(source)
text = recognizer.recognize_google(audio_data)
return text.encode('utf-8')
def text_to_speech(uploaded_file):
text = uploaded_file.read().decode("utf-8")
tts = gTTS(text)
output_audio = BytesIO()
tts.write_to_fp(output_audio)
return output_audio.getvalue()
def epub_to_pdf(uploaded_file):
from ebooklib import epub
from bs4 import BeautifulSoup
book = epub.read_epub(uploaded_file)
html_content = ""
for item in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):
soup = BeautifulSoup(item.get_body_content(), 'html.parser')
html_content += str(soup)
output_pdf = BytesIO()
HTML(string=html_content).write_pdf(output_pdf)
return output_pdf.getvalue()
# Display conversion options as cards
conversions = {
"Image to PDF": image_to_pdf,
"DOCX to PDF": docx_to_pdf_func,
"IPYNB to PDF": ipynb_to_pdf,
"DOCX to Image": docx_to_image,
"Image to DOCX": image_to_docx,
"PDF to Image": pdf_to_image,
"Text to PDF": text_to_pdf,
"Markdown to PDF": markdown_to_pdf,
"HTML to Image": html_to_image,
"CSV to Excel": csv_to_excel,
"Excel to CSV": excel_to_csv,
"Audio to Text": audio_to_text,
"Text to Speech": text_to_speech,
"EPUB to PDF": epub_to_pdf,
}
# Render each conversion option as a separate card
for conversion_name, conversion_func in conversions.items():
with st.container():
st.markdown(f"<div class='card'>", unsafe_allow_html=True)
st.markdown(f"<div class='card-title'>{conversion_name}</div>", unsafe_allow_html=True)
uploaded_file = st.file_uploader(f"Upload file for {conversion_name}", key=conversion_name)
if uploaded_file is not None:
if st.button(f"Convert {conversion_name}", key=f"button_{conversion_name}"):
if conversion_name == "PDF to Image":
images = conversion_func(uploaded_file)
for i, img in enumerate(images):
st.image(img, caption=f"Page {i+1}")
st.download_button(
label=f"Download Page {i+1}",
data=img,
file_name=f"output_page_{i+1}.png",
mime="image/png"
)
else:
output_data = conversion_func(uploaded_file)
output_mime = "application/pdf" if "PDF" in conversion_name else "image/png" if "Image" in conversion_name else "text/plain" if "Text" in conversion_name or "Markdown" in conversion_name else "application/vnd.openxmlformats-officedocument.wordprocessingml.document" if "DOCX" in conversion_name else "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" if "Excel" in conversion_name else "audio/mpeg" if "Speech" in conversion_name else "application/pdf"
output_ext = "pdf" if "PDF" in conversion_name else "png" if "Image" in conversion_name else "txt" if "Text" in conversion_name or "Markdown" in conversion_name else "docx" if "DOCX" in conversion_name else "xlsx" if "Excel" in conversion_name else "mp3" if "Speech" in conversion_name else "pdf"
st.download_button(
label="Download Converted File",
data=output_data,
file_name=f"output.{output_ext}",
mime=output_mime
)
st.markdown("</div>", unsafe_allow_html=True)