File size: 4,445 Bytes
21cd4b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import io
import os
import re
import glob
from datetime import datetime
from pathlib import Path

import streamlit as st
import pandas as pd
from PIL import Image
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
import mistune
from gtts import gTTS

# Page setup
st.set_page_config(page_title="PDF & Code Interpreter", layout="wide", page_icon="๐Ÿš€")

# Tabs
tab1, tab2 = st.tabs(["๐Ÿ“„ PDF Composer","๐Ÿงช CodeInterpreter"])

# --- Tab 1: PDF Composer ---
with tab1:
    st.title("๐Ÿ–ผ๏ธ๐Ÿ“ PDF Composer & Voice Generator")
    # Upload Markdown
    md_file = st.file_uploader("Upload Markdown (.md)", type=["md"] )
    md_text = ""
    if md_file:
        md_text = md_file.getvalue().decode("utf-8")
    else:
        md_text = st.text_area("Or enter markdown text", height=200)
    # Convert markdown to plain text
    plain = mistune.HTMLRenderer().render(mistune.create_markdown()) if not md_text.strip() else mistune.markdown(md_text)

    # Generate audio
    if st.button("๐Ÿ”Š Generate Voice Track MP3"):
        tts = gTTS(text=re.sub(r'<[^>]+>','', plain), lang='en')
        fname = f"voice_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp3"
        tts.save(fname)
        st.audio(fname)

    # Upload Images
    imgs = st.file_uploader("Upload Images", type=["png","jpg","jpeg"], accept_multiple_files=True)
    # Reorder images
    if imgs:
        df = pd.DataFrame([{"name":f.name,"order":i} for i,f in enumerate(imgs)])
        edited = st.experimental_data_editor(df, num_rows="fixed")
        ordered = [imgs[df.loc[i,'name'] == f.name][0] for i in range(len(df))]
    else:
        ordered = []

    # Generate PDF
    if st.button("๐Ÿ–‹๏ธ Generate PDF"):
        buf = io.BytesIO()
        c = canvas.Canvas(buf)
        # Add markdown text
        y = 800
        for line in re.sub(r'<[^>]+>','', plain).split('\n'):
            c.drawString(40,y,line)
            y -= 15
            if y<50:
                c.showPage(); y=800
        # Add images
        for imgf in ordered:
            img = Image.open(imgf)
            w,h = img.size
            c.showPage()
            c.drawImage(ImageReader(img),0,0,w,h)
        c.save(); buf.seek(0)
        pname = f"document_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
        st.download_button("โฌ‡๏ธ Download PDF", data=buf, file_name=pname, mime="application/pdf")

    # Show existing PDF files
    st.markdown("### Available PDFs")
    pdfs = sorted(glob.glob("*.pdf"))
    for p in pdfs:
        st.write(p, st.button("Download", key=p, args=(), kwargs={}, help="Download PDF"))

# --- Tab 2: CodeInterpreter ---
with tab2:
    import io, sys
    from contextlib import redirect_stdout
    DEFAULT_CODE = '''import streamlit as st
import random

st.title("๐Ÿงช Test Program")
st.markdown("Welcome to this simple test application!")

col1, col2 = st.columns(2)
with col1:
    number = st.number_input("Enter a number:",1,100,50)
    mult = st.slider("Select multiplier:",1,10,5)
    if st.button("Calculate"):
        st.success(f"Result: {number*mult}")
with col2:
    color = st.color_picker("Pick a color","#00f900")
    st.markdown(f'<div style="background-color:{color};padding:20px;">Color {color}</div>',unsafe_allow_html=True)
    if st.button("Random Number"):
        st.balloons(); st.write(random.randint(1,100))
'''
    def extract_python_code(md): return re.findall(r"```python\s*(.*?)```",md,re.DOTALL)
    def execute_code(code):
        buf = io.StringIO(); lv={}
        try:
            with redirect_stdout(buf): exec(code,{},lv)
            return buf.getvalue(),None
        except Exception as e: return None,str(e)
    st.title("๐Ÿ“ Python Code Executor")
    up = st.file_uploader("Upload .py or .md",type=['py','md'])
    code = DEFAULT_CODE if 'code' not in st.session_state else st.session_state.code
    if up:
        txt=up.getvalue().decode();
        if up.type=='text/markdown':
            blocks=extract_python_code(txt)
            code=blocks[0] if blocks else ''
        else: code=txt
        st.code(code,language='python')
    else:
        code=st.text_area("Code:",value=code,height=300)
    st.session_state.code=code
    if st.button("โ–ถ๏ธ Run Code"):
        out,err=execute_code(code)
        if err: st.error(err)
        elif out: st.code(out)
        else: st.success("Executed with no output.")
    if st.button("๐Ÿ—‘๏ธ Clear Code"): st.session_state.code=''; st.rerun()