Upload 4 files
Browse files- .gitattributes +2 -0
- app.py +1568 -0
- img_1.png +3 -0
- img_2.png +0 -0
- img_3.png +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
img_1.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
img_3.png filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,1568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 3 |
+
β PyStreamlit Converter Pro β Advanced Edition β
|
| 4 |
+
β Python / Jupyter β Streamlit App Converter & Analyzer β
|
| 5 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import streamlit as st
|
| 9 |
+
import nbformat
|
| 10 |
+
import ast
|
| 11 |
+
import re
|
| 12 |
+
import zipfile
|
| 13 |
+
import io
|
| 14 |
+
import hashlib
|
| 15 |
+
import time
|
| 16 |
+
import textwrap
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import List, Tuple, Dict, Any, Optional, Set
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
from collections import Counter
|
| 21 |
+
import difflib
|
| 22 |
+
|
| 23 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 24 |
+
# PAGE CONFIG (must be first Streamlit call)
|
| 25 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
st.set_page_config(
|
| 27 |
+
page_title="PyStreamlit Converter Pro",
|
| 28 |
+
page_icon="",
|
| 29 |
+
layout="wide",
|
| 30 |
+
initial_sidebar_state="expanded",
|
| 31 |
+
menu_items={
|
| 32 |
+
"About": "PyStreamlit Converter Pro β Transform Python & Jupyter code into Streamlit apps.",
|
| 33 |
+
},
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
+
# SESSION STATE
|
| 38 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
_DEFAULTS: Dict[str, Any] = {
|
| 40 |
+
"conversion_results": {},
|
| 41 |
+
"uploaded_files": [],
|
| 42 |
+
"uploaded_zip": None,
|
| 43 |
+
"theme": "dark",
|
| 44 |
+
"conversion_mode": "Hybrid (Recommended)",
|
| 45 |
+
"chart_library": "Auto-Detect",
|
| 46 |
+
"app_layout": "wide",
|
| 47 |
+
"sidebar_mode": "Auto (controls)",
|
| 48 |
+
"add_caching": True,
|
| 49 |
+
"add_error_handling": True,
|
| 50 |
+
"add_download_button": True,
|
| 51 |
+
"add_sidebar_controls": True,
|
| 52 |
+
"add_session_state": False,
|
| 53 |
+
"add_main_guard": False,
|
| 54 |
+
"preserve_comments": True,
|
| 55 |
+
"large_file_threshold": 200,
|
| 56 |
+
"conversion_history": [],
|
| 57 |
+
"stats": {
|
| 58 |
+
"total_files": 0,
|
| 59 |
+
"successful": 0,
|
| 60 |
+
"failed": 0,
|
| 61 |
+
"total_transformations": 0,
|
| 62 |
+
"session_start": datetime.now().isoformat(),
|
| 63 |
+
},
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
for k, v in _DEFAULTS.items():
|
| 67 |
+
if k not in st.session_state:
|
| 68 |
+
st.session_state[k] = v
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
+
# THEME & STYLING
|
| 73 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
def inject_css() -> None:
|
| 75 |
+
dark = st.session_state.theme == "dark"
|
| 76 |
+
bg0 = "#0a0c10" if dark else "#ffffff"
|
| 77 |
+
bg1 = "#12151c" if dark else "#f7f8fa"
|
| 78 |
+
bg2 = "#1a1e28" if dark else "#eef0f4"
|
| 79 |
+
border= "#2a2e3d" if dark else "#dde1ea"
|
| 80 |
+
txt0 = "#e8ecf4" if dark else "#12151c"
|
| 81 |
+
txt1 = "#8892a4" if dark else "#505870"
|
| 82 |
+
acc = "#4f8ef7"
|
| 83 |
+
acc2 = "#a78bfa"
|
| 84 |
+
suc = "#34d399"
|
| 85 |
+
warn = "#fbbf24"
|
| 86 |
+
err = "#f87171"
|
| 87 |
+
|
| 88 |
+
st.markdown(f"""
|
| 89 |
+
<style>
|
| 90 |
+
.stApp {{ background: {bg0}; color: {txt0}; font-family: 'Inter', sans-serif; }}
|
| 91 |
+
[data-testid="stSidebar"] {{ background: {bg1} !important; border-right: 1px solid {border}; }}
|
| 92 |
+
h1,h2,h3,h4,h5,h6 {{ color: {txt0} !important; font-weight: 700; }}
|
| 93 |
+
|
| 94 |
+
.pc-card {{
|
| 95 |
+
background: {bg1};
|
| 96 |
+
border: 1px solid {border};
|
| 97 |
+
border-radius: 12px;
|
| 98 |
+
padding: 20px 24px;
|
| 99 |
+
margin: 10px 0;
|
| 100 |
+
transition: box-shadow .2s;
|
| 101 |
+
}}
|
| 102 |
+
.pc-card:hover {{ box-shadow: 0 0 0 1px {acc}44; }}
|
| 103 |
+
|
| 104 |
+
.pc-metric {{
|
| 105 |
+
background: {bg2};
|
| 106 |
+
border-radius: 10px;
|
| 107 |
+
padding: 16px 20px;
|
| 108 |
+
border: 1px solid {border};
|
| 109 |
+
text-align: center;
|
| 110 |
+
}}
|
| 111 |
+
.pc-metric .val {{ font-size: 2em; font-weight: 800; color: {acc}; line-height: 1.1; }}
|
| 112 |
+
.pc-metric .lbl {{ font-size: 0.78em; color: {txt1}; text-transform: uppercase; letter-spacing: .06em; margin-top: 4px; }}
|
| 113 |
+
|
| 114 |
+
.pc-hero {{
|
| 115 |
+
background: linear-gradient(135deg, {acc}18 0%, {acc2}12 100%);
|
| 116 |
+
border: 1px solid {acc}33;
|
| 117 |
+
border-radius: 16px;
|
| 118 |
+
padding: 36px 40px;
|
| 119 |
+
text-align: center;
|
| 120 |
+
margin: 8px 0 24px;
|
| 121 |
+
position: relative;
|
| 122 |
+
overflow: hidden;
|
| 123 |
+
}}
|
| 124 |
+
.pc-hero::before {{
|
| 125 |
+
content: "";
|
| 126 |
+
position: absolute; inset: 0;
|
| 127 |
+
background: radial-gradient(ellipse at top left, {acc}10, transparent 60%);
|
| 128 |
+
pointer-events: none;
|
| 129 |
+
}}
|
| 130 |
+
.pc-hero h1 {{ font-size: 2.4em; margin: 0 0 10px; background: linear-gradient(90deg,{acc},{acc2}); -webkit-background-clip:text; -webkit-text-fill-color:transparent; }}
|
| 131 |
+
.pc-hero p {{ color: {txt1}; font-size: 1.05em; margin: 0 0 18px; }}
|
| 132 |
+
|
| 133 |
+
.pc-badge {{
|
| 134 |
+
display: inline-block;
|
| 135 |
+
padding: 3px 11px; border-radius: 20px;
|
| 136 |
+
font-size: .78em; font-weight: 600;
|
| 137 |
+
background: {acc}1a; color: {acc};
|
| 138 |
+
border: 1px solid {acc}44;
|
| 139 |
+
margin: 2px;
|
| 140 |
+
}}
|
| 141 |
+
.pc-badge-green {{ background: {suc}1a; color: {suc}; border-color: {suc}44; }}
|
| 142 |
+
.pc-badge-amber {{ background: {warn}1a; color: {warn}; border-color: {warn}44; }}
|
| 143 |
+
.pc-badge-red {{ background: {err}1a; color: {err}; border-color: {err}44; }}
|
| 144 |
+
.pc-badge-purple {{ background: {acc2}1a; color: {acc2}; border-color: {acc2}44; }}
|
| 145 |
+
|
| 146 |
+
.diff-add {{ background: {suc}22; color: {suc}; border-left: 3px solid {suc}; padding: 1px 8px; display:block; }}
|
| 147 |
+
.diff-rem {{ background: {err}22; color: {err}; border-left: 3px solid {err}; padding: 1px 8px; display:block; }}
|
| 148 |
+
.diff-same {{ color: {txt1}; padding: 1px 8px; display:block; }}
|
| 149 |
+
.diff-wrap {{ background: {bg2}; border: 1px solid {border}; border-radius: 8px; padding: 8px; font-family: monospace; font-size: .82em; max-height: 460px; overflow-y: auto; }}
|
| 150 |
+
|
| 151 |
+
.rep-item {{ display: flex; align-items: flex-start; gap: 8px; padding: 5px 0; font-size: .88em; }}
|
| 152 |
+
.rep-ok {{ color: {suc}; }}
|
| 153 |
+
.rep-warn {{ color: {warn}; }}
|
| 154 |
+
.rep-err {{ color: {err}; }}
|
| 155 |
+
.rep-info {{ color: {acc}; }}
|
| 156 |
+
|
| 157 |
+
.sidebar-logo {{ text-align:center; padding: 16px 0 8px; }}
|
| 158 |
+
.sidebar-logo .logo-icon {{ font-size: 2.8em; line-height: 1; }}
|
| 159 |
+
.sidebar-logo .logo-title {{ font-size: 1.1em; font-weight: 800; color: {acc}; margin-top: 4px; }}
|
| 160 |
+
.sidebar-logo .logo-sub {{ font-size: .7em; color: {txt1}; letter-spacing: .08em; }}
|
| 161 |
+
|
| 162 |
+
.stProgress > div > div > div {{ background: linear-gradient(90deg, {acc}, {acc2}) !important; }}
|
| 163 |
+
.stButton > button {{ border-radius: 8px !important; font-weight: 600 !important; transition: all .2s !important; }}
|
| 164 |
+
.stButton > button:hover {{ transform: translateY(-1px) !important; box-shadow: 0 4px 14px {acc}33 !important; }}
|
| 165 |
+
.stTabs [data-baseweb="tab-list"] {{ gap: 6px; }}
|
| 166 |
+
.stTabs [data-baseweb="tab"] {{ border-radius: 8px 8px 0 0 !important; padding: 10px 20px !important; font-weight: 600 !important; }}
|
| 167 |
+
.stCodeBlock {{ border-radius: 10px !important; border: 1px solid {border} !important; }}
|
| 168 |
+
[data-testid="stMetricValue"] {{ color: {acc} !important; font-weight: 700 !important; }}
|
| 169 |
+
.streamlit-expanderHeader {{ background: {bg2} !important; border-radius: 8px !important; font-weight: 600 !important; }}
|
| 170 |
+
|
| 171 |
+
.timeline-item {{
|
| 172 |
+
border-left: 2px solid {border};
|
| 173 |
+
padding: 6px 0 6px 16px;
|
| 174 |
+
margin-left: 8px;
|
| 175 |
+
position: relative;
|
| 176 |
+
}}
|
| 177 |
+
.timeline-item::before {{
|
| 178 |
+
content: "";
|
| 179 |
+
width: 8px; height: 8px;
|
| 180 |
+
background: {acc};
|
| 181 |
+
border-radius: 50%;
|
| 182 |
+
position: absolute; left: -5px; top: 10px;
|
| 183 |
+
}}
|
| 184 |
+
.timeline-item.ok::before {{ background: {suc}; }}
|
| 185 |
+
.timeline-item.err::before {{ background: {err}; }}
|
| 186 |
+
|
| 187 |
+
.health-bar-bg {{ background: {bg2}; border-radius: 4px; height: 6px; margin-top: 4px; }}
|
| 188 |
+
.health-bar-fg {{ height: 6px; border-radius: 4px; background: linear-gradient(90deg,{acc},{acc2}); }}
|
| 189 |
+
</style>
|
| 190 |
+
""", unsafe_allow_html=True)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
inject_css()
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
+
# CONVERTER CORE
|
| 198 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
+
|
| 200 |
+
class CodeAnalyzer:
|
| 201 |
+
"""
|
| 202 |
+
Static analysis of Python source code β extracts imports, functions,
|
| 203 |
+
classes, chart/ML/data libraries, transformable calls, and complexity metrics.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
def __init__(self, source: str):
|
| 207 |
+
self.source = source
|
| 208 |
+
self.tree: Optional[ast.Module] = None
|
| 209 |
+
try:
|
| 210 |
+
self.tree = ast.parse(source)
|
| 211 |
+
except SyntaxError:
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
def get_imports(self) -> List[str]:
|
| 215 |
+
if not self.tree:
|
| 216 |
+
return []
|
| 217 |
+
out = []
|
| 218 |
+
for node in ast.walk(self.tree):
|
| 219 |
+
if isinstance(node, ast.Import):
|
| 220 |
+
for alias in node.names:
|
| 221 |
+
out.append(alias.asname or alias.name)
|
| 222 |
+
elif isinstance(node, ast.ImportFrom) and node.module:
|
| 223 |
+
out.append(node.module)
|
| 224 |
+
return out
|
| 225 |
+
|
| 226 |
+
def get_functions(self) -> List[Dict]:
|
| 227 |
+
if not self.tree:
|
| 228 |
+
return []
|
| 229 |
+
fns = []
|
| 230 |
+
for node in ast.walk(self.tree):
|
| 231 |
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
| 232 |
+
doc = ast.get_docstring(node) or ""
|
| 233 |
+
fns.append({
|
| 234 |
+
"name": node.name,
|
| 235 |
+
"args": [a.arg for a in node.args.args],
|
| 236 |
+
"lineno": node.lineno,
|
| 237 |
+
"doc": (doc[:80] + "β¦") if len(doc) > 80 else doc,
|
| 238 |
+
"is_async": isinstance(node, ast.AsyncFunctionDef),
|
| 239 |
+
"body_lines": (node.end_lineno - node.lineno + 1) if hasattr(node, "end_lineno") else 0,
|
| 240 |
+
})
|
| 241 |
+
return fns
|
| 242 |
+
|
| 243 |
+
def get_classes(self) -> List[Dict]:
|
| 244 |
+
if not self.tree:
|
| 245 |
+
return []
|
| 246 |
+
out = []
|
| 247 |
+
for node in ast.walk(self.tree):
|
| 248 |
+
if isinstance(node, ast.ClassDef):
|
| 249 |
+
methods = [n.name for n in ast.walk(node) if isinstance(n, ast.FunctionDef)]
|
| 250 |
+
bases = []
|
| 251 |
+
for b in node.bases:
|
| 252 |
+
try:
|
| 253 |
+
bases.append(ast.unparse(b))
|
| 254 |
+
except Exception:
|
| 255 |
+
bases.append("?")
|
| 256 |
+
out.append({"name": node.name, "lineno": node.lineno, "methods": methods, "bases": bases})
|
| 257 |
+
return out
|
| 258 |
+
|
| 259 |
+
def detect_chart_libraries(self) -> List[str]:
|
| 260 |
+
s = self.source
|
| 261 |
+
libs = []
|
| 262 |
+
if "matplotlib" in s or "plt." in s: libs.append("matplotlib")
|
| 263 |
+
if "seaborn" in s or "sns." in s: libs.append("seaborn")
|
| 264 |
+
if "plotly" in s or "px." in s or "go." in s:libs.append("plotly")
|
| 265 |
+
if "altair" in s or "alt." in s: libs.append("altair")
|
| 266 |
+
if "bokeh" in s: libs.append("bokeh")
|
| 267 |
+
if "folium" in s: libs.append("folium")
|
| 268 |
+
return libs
|
| 269 |
+
|
| 270 |
+
def detect_ml_libraries(self) -> List[str]:
|
| 271 |
+
s = self.source
|
| 272 |
+
libs = []
|
| 273 |
+
if "sklearn" in s or "scikit" in s: libs.append("scikit-learn")
|
| 274 |
+
if "tensorflow" in s or "tf." in s: libs.append("tensorflow")
|
| 275 |
+
if "torch" in s: libs.append("pytorch")
|
| 276 |
+
if "xgboost" in s or "xgb." in s: libs.append("xgboost")
|
| 277 |
+
if "lightgbm" in s or "lgbm" in s: libs.append("lightgbm")
|
| 278 |
+
if "catboost" in s: libs.append("catboost")
|
| 279 |
+
if "transformers" in s: libs.append("transformers")
|
| 280 |
+
return libs
|
| 281 |
+
|
| 282 |
+
def detect_data_libraries(self) -> List[str]:
|
| 283 |
+
s = self.source
|
| 284 |
+
libs = []
|
| 285 |
+
if "pandas" in s or " pd." in s: libs.append("pandas")
|
| 286 |
+
if "numpy" in s or " np." in s: libs.append("numpy")
|
| 287 |
+
if "scipy" in s: libs.append("scipy")
|
| 288 |
+
if "polars" in s: libs.append("polars")
|
| 289 |
+
if "dask" in s: libs.append("dask")
|
| 290 |
+
return libs
|
| 291 |
+
|
| 292 |
+
def count_transformable_calls(self) -> Dict[str, int]:
|
| 293 |
+
counts: Counter = Counter()
|
| 294 |
+
for line in self.source.splitlines():
|
| 295 |
+
s = line.strip()
|
| 296 |
+
if re.match(r"print\s*\(", s): counts["print"] += 1
|
| 297 |
+
if re.match(r"display\s*\(", s): counts["display"] += 1
|
| 298 |
+
if re.match(r"plt\.show\s*\(", s): counts["plt.show"] += 1
|
| 299 |
+
if re.match(r"[a-zA-Z_]\w*\.show\s*\(", s): counts["fig.show"] += 1
|
| 300 |
+
if re.match(r"[a-zA-Z_]\w*\.(?:head|tail)\s*\(", s): counts["df.head/tail"] += 1
|
| 301 |
+
return dict(counts)
|
| 302 |
+
|
| 303 |
+
def compute_complexity(self) -> Dict[str, Any]:
|
| 304 |
+
lines = self.source.splitlines()
|
| 305 |
+
code_lines = [l for l in lines if l.strip() and not l.strip().startswith("#")]
|
| 306 |
+
comment_lines = [l for l in lines if l.strip().startswith("#")]
|
| 307 |
+
branch_kws = {"if", "elif", "for", "while", "try", "except", "with"}
|
| 308 |
+
branches = sum(1 for l in lines for kw in branch_kws if re.search(rf"\b{kw}\b", l))
|
| 309 |
+
return {
|
| 310 |
+
"total_lines": len(lines),
|
| 311 |
+
"code_lines": len(code_lines),
|
| 312 |
+
"comment_lines": len(comment_lines),
|
| 313 |
+
"blank_lines": len(lines) - len(code_lines) - len(comment_lines),
|
| 314 |
+
"cyclomatic": branches,
|
| 315 |
+
"functions": len(self.get_functions()),
|
| 316 |
+
"classes": len(self.get_classes()),
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
def suggest_widgets(self) -> List[Dict]:
|
| 320 |
+
"""Suggest Streamlit widgets for hard-coded literals."""
|
| 321 |
+
if not self.tree:
|
| 322 |
+
return []
|
| 323 |
+
out = []
|
| 324 |
+
for node in ast.walk(self.tree):
|
| 325 |
+
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant):
|
| 326 |
+
for target in node.targets:
|
| 327 |
+
try:
|
| 328 |
+
name = ast.unparse(target)
|
| 329 |
+
except Exception:
|
| 330 |
+
continue
|
| 331 |
+
val = node.value.value
|
| 332 |
+
if isinstance(val, bool):
|
| 333 |
+
out.append({"name": name, "widget": "st.checkbox", "default": val, "lineno": node.lineno})
|
| 334 |
+
elif isinstance(val, int) and 0 < val <= 1000:
|
| 335 |
+
out.append({"name": name, "widget": "st.slider", "default": val, "lineno": node.lineno})
|
| 336 |
+
elif isinstance(val, float) and 0.0 < val <= 1.0:
|
| 337 |
+
out.append({"name": name, "widget": "st.slider (float)", "default": val, "lineno": node.lineno})
|
| 338 |
+
elif isinstance(val, str) and len(val) < 80 and "\n" not in val:
|
| 339 |
+
out.append({"name": name, "widget": "st.text_input", "default": repr(val), "lineno": node.lineno})
|
| 340 |
+
return out[:15]
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 344 |
+
# AST Transformer
|
| 345 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 346 |
+
|
| 347 |
+
class EnhancedTransformer(ast.NodeTransformer):
|
| 348 |
+
"""AST transformer: printβst.write, displayβst.dataframe,
|
| 349 |
+
plt.showβst.pyplot, fig.showβst.plotly_chart, df.head/tailβst.dataframe,
|
| 350 |
+
plus optional @st.cache_data injection on loader functions."""
|
| 351 |
+
|
| 352 |
+
def __init__(self, source_lines: List[str], chart_library: str = "auto",
|
| 353 |
+
add_caching: bool = True):
|
| 354 |
+
self.source_lines = source_lines
|
| 355 |
+
self.chart_library = chart_library.lower()
|
| 356 |
+
self.add_caching = add_caching
|
| 357 |
+
self.conversion_log: List[str] = []
|
| 358 |
+
self.imports_needed: Set[str] = {"import streamlit as st"}
|
| 359 |
+
|
| 360 |
+
def _st(self, attr: str) -> ast.Attribute:
|
| 361 |
+
return ast.Attribute(value=ast.Name(id="st", ctx=ast.Load()), attr=attr, ctx=ast.Load())
|
| 362 |
+
|
| 363 |
+
def _call(self, func, args=None, kw=None) -> ast.Call:
|
| 364 |
+
return ast.Call(func=func, args=args or [], keywords=kw or [])
|
| 365 |
+
|
| 366 |
+
def _expr(self, val) -> ast.Expr:
|
| 367 |
+
return ast.Expr(value=val)
|
| 368 |
+
|
| 369 |
+
def visit_FunctionDef(self, node):
|
| 370 |
+
self.generic_visit(node)
|
| 371 |
+
if self.add_caching:
|
| 372 |
+
n = node.name.lower()
|
| 373 |
+
if any(kw in n for kw in ("load", "fetch", "read", "get_data", "query")):
|
| 374 |
+
node.decorator_list.insert(
|
| 375 |
+
0, ast.Attribute(value=ast.Name(id="st", ctx=ast.Load()),
|
| 376 |
+
attr="cache_data", ctx=ast.Load()))
|
| 377 |
+
self.conversion_log.append(f"β
Added @st.cache_data to {node.name}()")
|
| 378 |
+
return node
|
| 379 |
+
|
| 380 |
+
visit_AsyncFunctionDef = visit_FunctionDef
|
| 381 |
+
|
| 382 |
+
def visit_Expr(self, node):
|
| 383 |
+
self.generic_visit(node)
|
| 384 |
+
if not isinstance(node.value, ast.Call):
|
| 385 |
+
return node
|
| 386 |
+
call = node.value
|
| 387 |
+
|
| 388 |
+
# print β st.write
|
| 389 |
+
if isinstance(call.func, ast.Name) and call.func.id == "print":
|
| 390 |
+
call.func = self._st("write")
|
| 391 |
+
self.conversion_log.append("β
print() β st.write()")
|
| 392 |
+
return node
|
| 393 |
+
|
| 394 |
+
# display β st.dataframe or st.write
|
| 395 |
+
if isinstance(call.func, ast.Name) and call.func.id == "display":
|
| 396 |
+
fn = "dataframe" if (call.args and isinstance(call.args[0], ast.Name)) else "write"
|
| 397 |
+
call.func = self._st(fn)
|
| 398 |
+
self.conversion_log.append(f"β
display() β st.{fn}()")
|
| 399 |
+
return node
|
| 400 |
+
|
| 401 |
+
# plt.show() β st.pyplot(plt.gcf())
|
| 402 |
+
if (isinstance(call.func, ast.Attribute)
|
| 403 |
+
and isinstance(call.func.value, ast.Name)
|
| 404 |
+
and call.func.value.id == "plt"
|
| 405 |
+
and call.func.attr == "show"):
|
| 406 |
+
self.imports_needed.add("import matplotlib.pyplot as plt")
|
| 407 |
+
new = self._call(self._st("pyplot"), args=[
|
| 408 |
+
self._call(ast.Attribute(value=ast.Name(id="plt", ctx=ast.Load()), attr="gcf", ctx=ast.Load()))
|
| 409 |
+
])
|
| 410 |
+
self.conversion_log.append("β
plt.show() β st.pyplot(plt.gcf())")
|
| 411 |
+
return self._expr(new)
|
| 412 |
+
|
| 413 |
+
# <var>.show() β st.plotly_chart / st.altair_chart
|
| 414 |
+
if isinstance(call.func, ast.Attribute) and call.func.attr == "show":
|
| 415 |
+
if isinstance(call.func.value, ast.Name):
|
| 416 |
+
var = call.func.value.id
|
| 417 |
+
fn = "altair_chart" if self.chart_library == "altair" else "plotly_chart"
|
| 418 |
+
new = self._call(self._st(fn), args=[ast.Name(id=var, ctx=ast.Load())])
|
| 419 |
+
self.conversion_log.append(f"β
{var}.show() β st.{fn}()")
|
| 420 |
+
return self._expr(new)
|
| 421 |
+
|
| 422 |
+
# bokeh show(fig)
|
| 423 |
+
if isinstance(call.func, ast.Name) and call.func.id == "show" and call.args:
|
| 424 |
+
new = self._call(self._st("bokeh_chart"), args=call.args)
|
| 425 |
+
self.conversion_log.append("β
bokeh show() β st.bokeh_chart()")
|
| 426 |
+
return self._expr(new)
|
| 427 |
+
|
| 428 |
+
return node
|
| 429 |
+
|
| 430 |
+
def visit_Call(self, node):
|
| 431 |
+
self.generic_visit(node)
|
| 432 |
+
if isinstance(node.func, ast.Attribute):
|
| 433 |
+
if node.func.attr in ("head", "tail", "describe"):
|
| 434 |
+
if getattr(node, "_parent", None) is None:
|
| 435 |
+
wrapped = self._call(self._st("dataframe"), args=[node])
|
| 436 |
+
self.conversion_log.append(f"β
.{node.func.attr}() β st.dataframe()")
|
| 437 |
+
return wrapped
|
| 438 |
+
return node
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
# βββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 442 |
+
# Hybrid Converter
|
| 443 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 444 |
+
|
| 445 |
+
class HybridConverter:
|
| 446 |
+
"""
|
| 447 |
+
Three-pass conversion engine:
|
| 448 |
+
Pass 1 β AST transformation (structure-aware)
|
| 449 |
+
Pass 2 β Regex post-processing (magic cmds, misc patterns)
|
| 450 |
+
Pass 3 β Boilerplate injection (imports, page config, sidebar, error wrapping)
|
| 451 |
+
"""
|
| 452 |
+
|
| 453 |
+
def __init__(self, source: str, filename: str = "script", *,
|
| 454 |
+
conversion_mode: str = "hybrid",
|
| 455 |
+
chart_library: str = "auto",
|
| 456 |
+
app_layout: str = "wide",
|
| 457 |
+
sidebar_mode: str = "auto",
|
| 458 |
+
add_caching: bool = True,
|
| 459 |
+
add_error_handling: bool = True,
|
| 460 |
+
add_download_button: bool = True,
|
| 461 |
+
add_sidebar_controls: bool = True,
|
| 462 |
+
add_session_state: bool = False,
|
| 463 |
+
add_main_guard: bool = False,
|
| 464 |
+
preserve_comments: bool = True,
|
| 465 |
+
large_file_threshold: int = 200):
|
| 466 |
+
self.source = source
|
| 467 |
+
self.filename = filename
|
| 468 |
+
self.mode = conversion_mode.lower()
|
| 469 |
+
self.chart_library = chart_library.lower()
|
| 470 |
+
self.app_layout = app_layout
|
| 471 |
+
self.add_caching = add_caching
|
| 472 |
+
self.add_error_handling = add_error_handling
|
| 473 |
+
self.add_download_button = add_download_button
|
| 474 |
+
self.add_sidebar_controls = add_sidebar_controls
|
| 475 |
+
self.add_session_state = add_session_state
|
| 476 |
+
self.add_main_guard = add_main_guard
|
| 477 |
+
self.preserve_comments = preserve_comments
|
| 478 |
+
self.large_file_threshold = large_file_threshold * 1024
|
| 479 |
+
self.report: List[str] = []
|
| 480 |
+
self.imports_needed: Set[str] = set()
|
| 481 |
+
self.analyzer = CodeAnalyzer(source)
|
| 482 |
+
|
| 483 |
+
def convert(self) -> str:
|
| 484 |
+
self.report.append(f"βΉοΈ Source : {self.filename}")
|
| 485 |
+
self.report.append(f"βΉοΈ Mode : {self.mode}")
|
| 486 |
+
self.report.append(f"βΉοΈ Size : {len(self.source.encode())/1024:.1f} KB")
|
| 487 |
+
|
| 488 |
+
if "regex" in self.mode:
|
| 489 |
+
return self._regex_pass(self.source)
|
| 490 |
+
elif "ast" in self.mode:
|
| 491 |
+
return self._ast_pass()
|
| 492 |
+
else:
|
| 493 |
+
return self._hybrid_pass()
|
| 494 |
+
|
| 495 |
+
def get_report(self) -> List[str]:
|
| 496 |
+
return self.report
|
| 497 |
+
|
| 498 |
+
# ββ Passes βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 499 |
+
|
| 500 |
+
def _hybrid_pass(self) -> str:
|
| 501 |
+
try:
|
| 502 |
+
code = self._ast_core()
|
| 503 |
+
except Exception as exc:
|
| 504 |
+
self.report.append(f"β οΈ AST failed ({exc}), falling back to regex")
|
| 505 |
+
return self._regex_pass(self.source)
|
| 506 |
+
code = self._regex_cleanup(code)
|
| 507 |
+
return self._assemble(code)
|
| 508 |
+
|
| 509 |
+
def _ast_pass(self) -> str:
|
| 510 |
+
try:
|
| 511 |
+
return self._assemble(self._ast_core())
|
| 512 |
+
except Exception as exc:
|
| 513 |
+
self.report.append(f"β οΈ AST failed ({exc}), falling back to regex")
|
| 514 |
+
return self._regex_pass(self.source)
|
| 515 |
+
|
| 516 |
+
def _ast_core(self) -> str:
|
| 517 |
+
tree = ast.parse(self.source, filename=self.filename)
|
| 518 |
+
tx = EnhancedTransformer(
|
| 519 |
+
self.source.splitlines(keepends=True),
|
| 520 |
+
chart_library=self.chart_library,
|
| 521 |
+
add_caching=self.add_caching,
|
| 522 |
+
)
|
| 523 |
+
new_tree = tx.visit(tree)
|
| 524 |
+
ast.fix_missing_locations(new_tree)
|
| 525 |
+
self.imports_needed.update(tx.imports_needed)
|
| 526 |
+
self.report.extend(tx.conversion_log)
|
| 527 |
+
|
| 528 |
+
if hasattr(ast, "unparse"):
|
| 529 |
+
return ast.unparse(new_tree)
|
| 530 |
+
try:
|
| 531 |
+
import astor
|
| 532 |
+
return astor.to_source(new_tree)
|
| 533 |
+
except ImportError:
|
| 534 |
+
self.report.append("β οΈ Python < 3.9 & no astor; using regex")
|
| 535 |
+
return self._regex_pass(self.source)
|
| 536 |
+
|
| 537 |
+
def _regex_cleanup(self, code: str) -> str:
|
| 538 |
+
"""Light regex pass after AST to catch remaining patterns."""
|
| 539 |
+
out = []
|
| 540 |
+
for line in code.splitlines(keepends=True):
|
| 541 |
+
s = line.strip()
|
| 542 |
+
if s.startswith("%") or s.startswith("!"):
|
| 543 |
+
self.report.append(f"β
Removed magic/shell: {s[:40]}")
|
| 544 |
+
continue
|
| 545 |
+
out.append(line)
|
| 546 |
+
return "".join(out)
|
| 547 |
+
|
| 548 |
+
def _regex_pass(self, code: str) -> str:
|
| 549 |
+
"""Full line-by-line regex transformation."""
|
| 550 |
+
lines = code.splitlines(keepends=True)
|
| 551 |
+
out = []
|
| 552 |
+
in_mls = False
|
| 553 |
+
|
| 554 |
+
for line in lines:
|
| 555 |
+
s = line.strip()
|
| 556 |
+
ind = len(line) - len(line.lstrip())
|
| 557 |
+
sp = " " * ind
|
| 558 |
+
|
| 559 |
+
if s.startswith("%") or s.startswith("!"):
|
| 560 |
+
self.report.append(f"β
Removed magic/shell: {s[:40]}")
|
| 561 |
+
continue
|
| 562 |
+
|
| 563 |
+
if '"""' in line or "'''" in line:
|
| 564 |
+
tq = '"""' if '"""' in line else "'''"
|
| 565 |
+
if line.count(tq) % 2 == 1:
|
| 566 |
+
in_mls = not in_mls
|
| 567 |
+
out.append(line); continue
|
| 568 |
+
|
| 569 |
+
if in_mls:
|
| 570 |
+
out.append(line); continue
|
| 571 |
+
|
| 572 |
+
if re.match(r"^\s*print\s*\(", s):
|
| 573 |
+
out.append(re.sub(r"\bprint\s*\(", "st.write(", line, count=1))
|
| 574 |
+
self.report.append("β
print() β st.write()")
|
| 575 |
+
self.imports_needed.add("import streamlit as st")
|
| 576 |
+
continue
|
| 577 |
+
|
| 578 |
+
if re.match(r"^\s*display\s*\(", s):
|
| 579 |
+
out.append(re.sub(r"\bdisplay\s*\(", "st.dataframe(", line, count=1))
|
| 580 |
+
self.report.append("β
display() β st.dataframe()")
|
| 581 |
+
self.imports_needed.add("import streamlit as st")
|
| 582 |
+
continue
|
| 583 |
+
|
| 584 |
+
if re.match(r"^\s*plt\.show\s*\(\s*\)", s):
|
| 585 |
+
out.append(f"{sp}st.pyplot(plt.gcf())\n")
|
| 586 |
+
self.report.append("β
plt.show() β st.pyplot(plt.gcf())")
|
| 587 |
+
self.imports_needed.add("import streamlit as st")
|
| 588 |
+
continue
|
| 589 |
+
|
| 590 |
+
m = re.match(r"^\s*([a-zA-Z_]\w*)\.show\s*\(\s*\)\s*$", s)
|
| 591 |
+
if m and m.group(1) != "plt":
|
| 592 |
+
var = m.group(1)
|
| 593 |
+
out.append(f"{sp}st.plotly_chart({var})\n")
|
| 594 |
+
self.report.append(f"β
{var}.show() β st.plotly_chart({var})")
|
| 595 |
+
self.imports_needed.add("import streamlit as st")
|
| 596 |
+
continue
|
| 597 |
+
|
| 598 |
+
m2 = re.match(r"^\s*([a-zA-Z_]\w*\.(?:head|tail|describe)\s*\([^)]*\))\s*$", s)
|
| 599 |
+
if m2:
|
| 600 |
+
out.append(f"{sp}st.dataframe({m2.group(1)})\n")
|
| 601 |
+
self.report.append("β
DataFrame view β st.dataframe()")
|
| 602 |
+
self.imports_needed.add("import streamlit as st")
|
| 603 |
+
continue
|
| 604 |
+
|
| 605 |
+
out.append(line)
|
| 606 |
+
|
| 607 |
+
result = "".join(out)
|
| 608 |
+
self._detect_imports(self.source)
|
| 609 |
+
return self._assemble(result)
|
| 610 |
+
|
| 611 |
+
# ββ Import Detection βββββββββββββββββββββββββββββββββββββββ
|
| 612 |
+
|
| 613 |
+
def _detect_imports(self, code: str) -> None:
|
| 614 |
+
self.imports_needed.add("import streamlit as st")
|
| 615 |
+
checks = [
|
| 616 |
+
(r"\bplt\.", "import matplotlib.pyplot as plt"),
|
| 617 |
+
("matplotlib", "import matplotlib.pyplot as plt"),
|
| 618 |
+
(r"\bsns\.", "import seaborn as sns"),
|
| 619 |
+
("seaborn", "import seaborn as sns"),
|
| 620 |
+
(r"\bpx\.", "import plotly.express as px"),
|
| 621 |
+
(r"\bgo\.", "import plotly.graph_objects as go"),
|
| 622 |
+
("plotly", "import plotly.express as px"),
|
| 623 |
+
(r"\bpd\.", "import pandas as pd"),
|
| 624 |
+
("pandas", "import pandas as pd"),
|
| 625 |
+
(r"\bnp\.", "import numpy as np"),
|
| 626 |
+
("numpy", "import numpy as np"),
|
| 627 |
+
(r"\balt\.", "import altair as alt"),
|
| 628 |
+
("altair", "import altair as alt"),
|
| 629 |
+
]
|
| 630 |
+
for pattern, imp in checks:
|
| 631 |
+
if re.search(pattern, code):
|
| 632 |
+
self.imports_needed.add(imp)
|
| 633 |
+
|
| 634 |
+
# ββ Sidebar Widgets ββββββββββββββββββββββββββββββββββββββββ
|
| 635 |
+
|
| 636 |
+
def _build_sidebar(self) -> str:
|
| 637 |
+
suggestions = self.analyzer.suggest_widgets()
|
| 638 |
+
if not suggestions or not self.add_sidebar_controls:
|
| 639 |
+
return ""
|
| 640 |
+
lines = [
|
| 641 |
+
"\n# ββ Auto-generated Sidebar Controls ββββββββββββββββββ",
|
| 642 |
+
"with st.sidebar:",
|
| 643 |
+
' st.markdown("### βοΈ Parameters")',
|
| 644 |
+
]
|
| 645 |
+
for s in suggestions[:8]:
|
| 646 |
+
name = s["name"]
|
| 647 |
+
w = s["widget"]
|
| 648 |
+
d = s["default"]
|
| 649 |
+
label = repr(name.replace("_", " ").title())
|
| 650 |
+
if "checkbox" in w:
|
| 651 |
+
lines.append(f" {name} = st.checkbox({label}, value={d})")
|
| 652 |
+
elif "float" in w:
|
| 653 |
+
lines.append(f" {name} = st.slider({label}, 0.0, 1.0, float({d}))")
|
| 654 |
+
elif "slider" in w:
|
| 655 |
+
mx = max(int(d) * 10, 100)
|
| 656 |
+
lines.append(f" {name} = st.slider({label}, 0, {mx}, {d})")
|
| 657 |
+
else:
|
| 658 |
+
lines.append(f" {name} = st.text_input({label}, value={d})")
|
| 659 |
+
return "\n".join(lines)
|
| 660 |
+
|
| 661 |
+
# ββ Assembly βββββββββββββββββββββββββββββββββββββββββββββ
|
| 662 |
+
|
| 663 |
+
def _assemble(self, body: str) -> str:
|
| 664 |
+
self._detect_imports(self.source)
|
| 665 |
+
|
| 666 |
+
stem = Path(self.filename).stem.replace("_", " ").title()
|
| 667 |
+
chart_icon = "π" if self.analyzer.detect_chart_libraries() else ""
|
| 668 |
+
|
| 669 |
+
# separate out existing imports from body
|
| 670 |
+
existing, clean_body = [], []
|
| 671 |
+
for line in body.splitlines(keepends=True):
|
| 672 |
+
if re.match(r"^\s*(import |from )", line):
|
| 673 |
+
existing.append(line.strip())
|
| 674 |
+
else:
|
| 675 |
+
clean_body.append(line)
|
| 676 |
+
body_clean = "".join(clean_body)
|
| 677 |
+
|
| 678 |
+
all_imp = sorted(set(existing) | {
|
| 679 |
+
imp for imp in self.imports_needed
|
| 680 |
+
if not any(imp.split()[1].split(".")[0] in ex for ex in existing)
|
| 681 |
+
})
|
| 682 |
+
|
| 683 |
+
session_block = (
|
| 684 |
+
"\n# ββ Session State ββββββββββββββββββββββββββββββββββββ\n"
|
| 685 |
+
"if 'initialized' not in st.session_state:\n"
|
| 686 |
+
" st.session_state.initialized = True\n"
|
| 687 |
+
) if self.add_session_state else ""
|
| 688 |
+
|
| 689 |
+
sidebar_block = self._build_sidebar()
|
| 690 |
+
|
| 691 |
+
dl_block = (
|
| 692 |
+
"\n\n# ββ Export ββββββββββββββββββββββββββββββββββββββββββββ\n"
|
| 693 |
+
"st.divider()\n"
|
| 694 |
+
"# Uncomment & replace `df` with your DataFrame:\n"
|
| 695 |
+
"# st.download_button('β¬οΈ Download CSV', df.to_csv(index=False), 'output.csv', 'text/csv')\n"
|
| 696 |
+
) if self.add_download_button else ""
|
| 697 |
+
|
| 698 |
+
header = textwrap.dedent(f"""\
|
| 699 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 700 |
+
# AUTO-GENERATED STREAMLIT APP
|
| 701 |
+
# Source : {self.filename}
|
| 702 |
+
# Converted: {datetime.now().strftime('%Y-%m-%d %H:%M')}
|
| 703 |
+
# Tool : PyStreamlit Converter Pro
|
| 704 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 705 |
+
|
| 706 |
+
{chr(10).join(all_imp)}
|
| 707 |
+
|
| 708 |
+
st.set_page_config(
|
| 709 |
+
page_title="{stem}",
|
| 710 |
+
page_icon="{chart_icon}",
|
| 711 |
+
layout="{self.app_layout}",
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
st.title("{chart_icon} {stem}")
|
| 715 |
+
st.caption("_Converted from `{self.filename}` Β· PyStreamlit Converter Pro_")
|
| 716 |
+
st.divider()
|
| 717 |
+
""")
|
| 718 |
+
|
| 719 |
+
if self.add_error_handling:
|
| 720 |
+
# Enhanced error handling with more specific error messages
|
| 721 |
+
indented = textwrap.indent(body_clean.strip(), " ")
|
| 722 |
+
main = (
|
| 723 |
+
"\ntry:\n"
|
| 724 |
+
f"{indented}\n"
|
| 725 |
+
"except FileNotFoundError as _e:\n"
|
| 726 |
+
" st.error(f'β File not found: {_e}')\n"
|
| 727 |
+
" st.info('π‘ Make sure all required data files are included in your app')\n"
|
| 728 |
+
" with st.expander('π Full error details'):\n"
|
| 729 |
+
" import traceback\n"
|
| 730 |
+
" st.code(traceback.format_exc(), language='python')\n"
|
| 731 |
+
"except ModuleNotFoundError as _e:\n"
|
| 732 |
+
" st.error(f'β Missing module: {_e.name}')\n"
|
| 733 |
+
" st.info('π‘ Install missing packages with: pip install package_name')\n"
|
| 734 |
+
" with st.expander('π Full error details'):\n"
|
| 735 |
+
" import traceback\n"
|
| 736 |
+
" st.code(traceback.format_exc(), language='python')\n"
|
| 737 |
+
"except Exception as _e:\n"
|
| 738 |
+
" st.error(f'β οΈ Runtime error: {_e}')\n"
|
| 739 |
+
" with st.expander('π Full error details'):\n"
|
| 740 |
+
" import traceback\n"
|
| 741 |
+
" st.code(traceback.format_exc(), language='python')\n"
|
| 742 |
+
)
|
| 743 |
+
else:
|
| 744 |
+
main = "\n" + body_clean
|
| 745 |
+
|
| 746 |
+
if self.add_main_guard:
|
| 747 |
+
main = "\nif __name__ == '__main__':\n" + textwrap.indent(main, " ")
|
| 748 |
+
|
| 749 |
+
return header + session_block + sidebar_block + main + dl_block
|
| 750 |
+
|
| 751 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 752 |
+
# Notebook Extractor
|
| 753 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 754 |
+
|
| 755 |
+
def extract_notebook(content: bytes, preserve_markdown: bool = True) -> str:
|
| 756 |
+
try:
|
| 757 |
+
nb = nbformat.reads(content.decode("utf-8"), as_version=4)
|
| 758 |
+
except Exception as exc:
|
| 759 |
+
raise ValueError(f"Invalid notebook: {exc}") from exc
|
| 760 |
+
|
| 761 |
+
parts = []
|
| 762 |
+
for i, cell in enumerate(nb.cells, 1):
|
| 763 |
+
if cell.cell_type == "markdown" and preserve_markdown:
|
| 764 |
+
src = cell.source.replace("\\", "\\\\").replace('"', '\\"')
|
| 765 |
+
parts.append(f'\n# ββ Markdown cell {i} ββββββββββββββββββββββββββββββββ')
|
| 766 |
+
parts.append(f'st.markdown("""\n{cell.source}\n""")')
|
| 767 |
+
elif cell.cell_type == "code" and cell.source.strip():
|
| 768 |
+
parts.append(f"\n# ββ Code cell {i} ββββββββββββββββββββββββββββββββββ")
|
| 769 |
+
parts.append(cell.source.strip())
|
| 770 |
+
|
| 771 |
+
return "\n\n".join(parts)
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 775 |
+
# Cached File Processing
|
| 776 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 777 |
+
|
| 778 |
+
@st.cache_data(show_spinner=False)
|
| 779 |
+
def process_file(
|
| 780 |
+
file_bytes: bytes, filename: str, file_hash: str,
|
| 781 |
+
conversion_mode: str, chart_library: str, app_layout: str,
|
| 782 |
+
sidebar_mode: str, add_caching: bool, add_error_handling: bool,
|
| 783 |
+
add_download_button: bool, add_sidebar_controls: bool,
|
| 784 |
+
add_session_state: bool, add_main_guard: bool,
|
| 785 |
+
preserve_comments: bool, large_file_threshold: int,
|
| 786 |
+
) -> Tuple[str, str, List[str]]:
|
| 787 |
+
ext = Path(filename).suffix.lower()
|
| 788 |
+
try:
|
| 789 |
+
original = (extract_notebook(file_bytes, preserve_markdown=preserve_comments)
|
| 790 |
+
if ext == ".ipynb" else file_bytes.decode("utf-8"))
|
| 791 |
+
except Exception as exc:
|
| 792 |
+
return f"# Decode error: {exc}", "", [f"β {exc}"]
|
| 793 |
+
|
| 794 |
+
converter = HybridConverter(
|
| 795 |
+
original, filename,
|
| 796 |
+
conversion_mode=conversion_mode, chart_library=chart_library,
|
| 797 |
+
app_layout=app_layout, sidebar_mode=sidebar_mode,
|
| 798 |
+
add_caching=add_caching, add_error_handling=add_error_handling,
|
| 799 |
+
add_download_button=add_download_button, add_sidebar_controls=add_sidebar_controls,
|
| 800 |
+
add_session_state=add_session_state, add_main_guard=add_main_guard,
|
| 801 |
+
preserve_comments=preserve_comments, large_file_threshold=large_file_threshold,
|
| 802 |
+
)
|
| 803 |
+
try:
|
| 804 |
+
return converter.convert(), original, converter.get_report()
|
| 805 |
+
except Exception as exc:
|
| 806 |
+
return f"# Conversion error: {exc}", original, [f"β {exc}"]
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _conv_kwargs() -> Dict:
|
| 810 |
+
return dict(
|
| 811 |
+
conversion_mode=st.session_state.conversion_mode.lower(),
|
| 812 |
+
chart_library=st.session_state.chart_library.lower(),
|
| 813 |
+
app_layout=st.session_state.app_layout,
|
| 814 |
+
sidebar_mode=st.session_state.sidebar_mode,
|
| 815 |
+
add_caching=st.session_state.add_caching,
|
| 816 |
+
add_error_handling=st.session_state.add_error_handling,
|
| 817 |
+
add_download_button=st.session_state.add_download_button,
|
| 818 |
+
add_sidebar_controls=st.session_state.add_sidebar_controls,
|
| 819 |
+
add_session_state=st.session_state.add_session_state,
|
| 820 |
+
add_main_guard=st.session_state.add_main_guard,
|
| 821 |
+
preserve_comments=st.session_state.preserve_comments,
|
| 822 |
+
large_file_threshold=st.session_state.large_file_threshold,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def _process_uploaded(uf) -> Tuple[str, str, List[str]]:
|
| 827 |
+
raw = uf.getvalue()
|
| 828 |
+
fh = hashlib.md5(raw).hexdigest()[:8]
|
| 829 |
+
return process_file(raw, uf.name, fh, **_conv_kwargs())
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 833 |
+
# Diff Builder
|
| 834 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 835 |
+
|
| 836 |
+
def build_diff_html(original: str, converted: str, context: int = 4) -> str:
|
| 837 |
+
diff = list(difflib.unified_diff(
|
| 838 |
+
original.splitlines(), converted.splitlines(), lineterm="", n=context))
|
| 839 |
+
if not diff:
|
| 840 |
+
return "<p>No differences found.</p>"
|
| 841 |
+
rows = []
|
| 842 |
+
for line in diff[2:]:
|
| 843 |
+
if line.startswith("+"):
|
| 844 |
+
rows.append(f'<span class="diff-add">+ {line[1:]}</span>')
|
| 845 |
+
elif line.startswith("-"):
|
| 846 |
+
rows.append(f'<span class="diff-rem">- {line[1:]}</span>')
|
| 847 |
+
elif line.startswith("@@"):
|
| 848 |
+
rows.append(f'<span style="color:#8892a4;padding:1px 8px;display:block">@@ {line[2:]} @@</span>')
|
| 849 |
+
else:
|
| 850 |
+
rows.append(f'<span class="diff-same"> {line}</span>')
|
| 851 |
+
return f'<div class="diff-wrap">{"".join(rows)}</div>'
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
@st.cache_data
|
| 855 |
+
def get_sample_script() -> bytes:
|
| 856 |
+
return b"""\
|
| 857 |
+
import pandas as pd
|
| 858 |
+
import numpy as np
|
| 859 |
+
import matplotlib.pyplot as plt
|
| 860 |
+
|
| 861 |
+
# Configuration
|
| 862 |
+
n_points = 500
|
| 863 |
+
random_seed = 42
|
| 864 |
+
show_grid = True
|
| 865 |
+
plot_title = "Time Series Analysis"
|
| 866 |
+
|
| 867 |
+
np.random.seed(random_seed)
|
| 868 |
+
dates = pd.date_range('2023-01-01', periods=n_points, freq='D')
|
| 869 |
+
values = np.cumsum(np.random.randn(n_points)) + 100
|
| 870 |
+
df = pd.DataFrame({'date': dates, 'value': values,
|
| 871 |
+
'volume': np.abs(np.random.randn(n_points)) * 1000})
|
| 872 |
+
|
| 873 |
+
print("Dataset overview:")
|
| 874 |
+
print(f" Date range : {df['date'].min().date()} to {df['date'].max().date()}")
|
| 875 |
+
print(f" Mean value : {df['value'].mean():.2f}")
|
| 876 |
+
|
| 877 |
+
display(df.head(10))
|
| 878 |
+
display(df.describe())
|
| 879 |
+
|
| 880 |
+
fig, axes = plt.subplots(2, 1, figsize=(12, 8))
|
| 881 |
+
axes[0].plot(df['date'], df['value'], linewidth=1.5, color='#4f8ef7')
|
| 882 |
+
axes[0].set_title(plot_title)
|
| 883 |
+
axes[0].grid(show_grid)
|
| 884 |
+
axes[1].bar(df['date'], df['volume'], color='#a78bfa', alpha=0.7)
|
| 885 |
+
axes[1].set_title('Volume')
|
| 886 |
+
plt.tight_layout()
|
| 887 |
+
plt.show()
|
| 888 |
+
"""
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 892 |
+
# UI COMPONENTS
|
| 893 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 894 |
+
|
| 895 |
+
def metric_card(title: str, value: str, icon: str = "π", subtitle: str = "") -> None:
|
| 896 |
+
sub = f'<div style="font-size:.72em;opacity:.7;margin-top:2px">{subtitle}</div>' if subtitle else ""
|
| 897 |
+
st.markdown(f"""
|
| 898 |
+
<div class="pc-metric">
|
| 899 |
+
<div style="font-size:1.6em;line-height:1">{icon}</div>
|
| 900 |
+
<div class="val">{value}</div>
|
| 901 |
+
<div class="lbl">{title}</div>{sub}
|
| 902 |
+
</div>""", unsafe_allow_html=True)
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
def badge(text: str, variant: str = "") -> None:
|
| 906 |
+
cls = f"pc-badge-{variant}" if variant else "pc-badge"
|
| 907 |
+
st.markdown(f'<span class="pc-badge {cls}">{text}</span>', unsafe_allow_html=True)
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def render_report(items: List[str]) -> None:
|
| 911 |
+
for item in items:
|
| 912 |
+
if "β
" in item: icon, cls = "β", "rep-ok"
|
| 913 |
+
elif "β οΈ" in item: icon, cls = "!", "rep-warn"
|
| 914 |
+
elif "β" in item: icon, cls = "β", "rep-err"
|
| 915 |
+
else: icon, cls = "i", "rep-info"
|
| 916 |
+
st.markdown(
|
| 917 |
+
f'<div class="rep-item"><span class="{cls}">[{icon}]</span>'
|
| 918 |
+
f'<span>{item}</span></div>',
|
| 919 |
+
unsafe_allow_html=True,
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
def render_analysis(analyzer: CodeAnalyzer, filename: str) -> None:
|
| 924 |
+
cmx = analyzer.compute_complexity()
|
| 925 |
+
cols = st.columns(5)
|
| 926 |
+
for col, (title, val, icon) in zip(cols, [
|
| 927 |
+
("Total Lines", str(cmx["total_lines"]), "π"),
|
| 928 |
+
("Code Lines", str(cmx["code_lines"]), "π»"),
|
| 929 |
+
("Functions", str(cmx["functions"]), "β‘"),
|
| 930 |
+
("Classes", str(cmx["classes"]), "ποΈ"),
|
| 931 |
+
("Branches", str(cmx["cyclomatic"]), "π"),
|
| 932 |
+
]):
|
| 933 |
+
with col:
|
| 934 |
+
metric_card(title, val, icon)
|
| 935 |
+
|
| 936 |
+
st.markdown("")
|
| 937 |
+
ca, cb = st.columns(2)
|
| 938 |
+
|
| 939 |
+
with ca:
|
| 940 |
+
st.markdown("**π¦ Detected Libraries**")
|
| 941 |
+
for cat, fn in [("Charts", analyzer.detect_chart_libraries),
|
| 942 |
+
("ML/AI", analyzer.detect_ml_libraries),
|
| 943 |
+
("Data", analyzer.detect_data_libraries)]:
|
| 944 |
+
detected = fn()
|
| 945 |
+
if detected:
|
| 946 |
+
st.markdown(f"_{cat}_: " + " ".join(f"`{l}`" for l in detected))
|
| 947 |
+
|
| 948 |
+
st.markdown("**π’ Transformable Calls**")
|
| 949 |
+
counts = analyzer.count_transformable_calls()
|
| 950 |
+
if counts:
|
| 951 |
+
for name, n in counts.items():
|
| 952 |
+
st.markdown(f"- `{name}` Γ {n}")
|
| 953 |
+
else:
|
| 954 |
+
st.caption("None detected.")
|
| 955 |
+
|
| 956 |
+
with cb:
|
| 957 |
+
st.markdown("**π§© Functions**")
|
| 958 |
+
fns = analyzer.get_functions()
|
| 959 |
+
if fns:
|
| 960 |
+
st.dataframe(
|
| 961 |
+
[{"Name": f["name"], "Args": ", ".join(f["args"]) or "β",
|
| 962 |
+
"Lines": f["body_lines"], "Async": "β" if f["is_async"] else ""}
|
| 963 |
+
for f in fns[:12]],
|
| 964 |
+
use_container_width=True, hide_index=True,
|
| 965 |
+
)
|
| 966 |
+
else:
|
| 967 |
+
st.caption("No functions found.")
|
| 968 |
+
|
| 969 |
+
st.markdown("**π‘ Widget Suggestions**")
|
| 970 |
+
sug = analyzer.suggest_widgets()
|
| 971 |
+
if sug:
|
| 972 |
+
st.dataframe(
|
| 973 |
+
[{"Variable": s["name"], "Widget": s["widget"],
|
| 974 |
+
"Default": str(s["default"]), "Line": s["lineno"]} for s in sug],
|
| 975 |
+
use_container_width=True, hide_index=True,
|
| 976 |
+
)
|
| 977 |
+
else:
|
| 978 |
+
st.caption("No hard-coded parameters found.")
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 982 |
+
# SIDEBAR
|
| 983 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 984 |
+
|
| 985 |
+
with st.sidebar:
|
| 986 |
+
st.markdown("""
|
| 987 |
+
<div class="sidebar-logo">
|
| 988 |
+
<div class="logo-icon"></div>
|
| 989 |
+
<div class="logo-title">PyStreamlit</div>
|
| 990 |
+
<div class="logo-sub">CONVERTER PRO</div>
|
| 991 |
+
</div>""", unsafe_allow_html=True)
|
| 992 |
+
st.divider()
|
| 993 |
+
|
| 994 |
+
c1, c2 = st.columns(2)
|
| 995 |
+
with c1:
|
| 996 |
+
ti = "βοΈ" if st.session_state.theme == "dark" else "π"
|
| 997 |
+
if st.button(ti, use_container_width=True, help="Toggle theme"):
|
| 998 |
+
st.session_state.theme = "light" if st.session_state.theme == "dark" else "dark"
|
| 999 |
+
st.rerun()
|
| 1000 |
+
with c2:
|
| 1001 |
+
if st.button("π", use_container_width=True, help="Reset"):
|
| 1002 |
+
for k in list(st.session_state.keys()):
|
| 1003 |
+
del st.session_state[k]
|
| 1004 |
+
st.rerun()
|
| 1005 |
+
|
| 1006 |
+
st.divider()
|
| 1007 |
+
st.markdown("### π₯ Upload")
|
| 1008 |
+
umode = st.radio("Type", ["π Files", "π¦ ZIP"], label_visibility="collapsed")
|
| 1009 |
+
|
| 1010 |
+
if umode == "π Files":
|
| 1011 |
+
files = st.file_uploader("Python / Notebook files",
|
| 1012 |
+
type=["py", "ipynb"], accept_multiple_files=True,
|
| 1013 |
+
label_visibility="collapsed")
|
| 1014 |
+
st.session_state.uploaded_files = files or []
|
| 1015 |
+
st.session_state.uploaded_zip = None
|
| 1016 |
+
else:
|
| 1017 |
+
zf = st.file_uploader("ZIP archive", type=["zip"], label_visibility="collapsed")
|
| 1018 |
+
st.session_state.uploaded_zip = zf
|
| 1019 |
+
st.session_state.uploaded_files = []
|
| 1020 |
+
|
| 1021 |
+
st.divider()
|
| 1022 |
+
st.markdown("### βοΈ Settings")
|
| 1023 |
+
|
| 1024 |
+
mode_opts = ["Hybrid (Recommended)", "AST (Precise)", "Regex (Fast)"]
|
| 1025 |
+
st.session_state.conversion_mode = st.selectbox(
|
| 1026 |
+
"Strategy", mode_opts,
|
| 1027 |
+
index=mode_opts.index(st.session_state.conversion_mode)
|
| 1028 |
+
if st.session_state.conversion_mode in mode_opts else 0,
|
| 1029 |
+
)
|
| 1030 |
+
st.session_state.chart_library = st.selectbox(
|
| 1031 |
+
"Chart library", ["Auto-Detect", "Plotly", "Altair", "Matplotlib"])
|
| 1032 |
+
st.session_state.app_layout = st.selectbox("App layout", ["wide", "centered"])
|
| 1033 |
+
|
| 1034 |
+
with st.expander("π§ Advanced"):
|
| 1035 |
+
st.session_state.add_caching = st.checkbox("@st.cache_data on loaders", value=st.session_state.add_caching)
|
| 1036 |
+
st.session_state.add_error_handling = st.checkbox("Error handling wrapper", value=st.session_state.add_error_handling)
|
| 1037 |
+
st.session_state.add_sidebar_controls = st.checkbox("Auto sidebar widgets", value=st.session_state.add_sidebar_controls)
|
| 1038 |
+
st.session_state.add_download_button = st.checkbox("Download button stub", value=st.session_state.add_download_button)
|
| 1039 |
+
st.session_state.add_session_state = st.checkbox("Session state init", value=st.session_state.add_session_state)
|
| 1040 |
+
st.session_state.add_main_guard = st.checkbox("if __name__ == '__main__'", value=st.session_state.add_main_guard)
|
| 1041 |
+
st.session_state.preserve_comments = st.checkbox("Preserve comments", value=st.session_state.preserve_comments)
|
| 1042 |
+
st.session_state.large_file_threshold = st.slider(
|
| 1043 |
+
"Large file threshold (KB)", 50, 5000,
|
| 1044 |
+
value=st.session_state.large_file_threshold, step=50)
|
| 1045 |
+
|
| 1046 |
+
st.divider()
|
| 1047 |
+
st.markdown("### π§ͺ Samples")
|
| 1048 |
+
sc1, sc2 = st.columns(2)
|
| 1049 |
+
with sc1:
|
| 1050 |
+
if st.button("π Notebook", use_container_width=True):
|
| 1051 |
+
raw = get_sample_notebook()
|
| 1052 |
+
buf = io.BytesIO(raw); buf.name = "sample_analysis.ipynb"
|
| 1053 |
+
st.session_state.uploaded_files = [buf]
|
| 1054 |
+
st.session_state.uploaded_zip = None
|
| 1055 |
+
st.rerun()
|
| 1056 |
+
with sc2:
|
| 1057 |
+
if st.button("π Script", use_container_width=True):
|
| 1058 |
+
raw = get_sample_script()
|
| 1059 |
+
buf = io.BytesIO(raw); buf.name = "sample_timeseries.py"
|
| 1060 |
+
st.session_state.uploaded_files = [buf]
|
| 1061 |
+
st.session_state.uploaded_zip = None
|
| 1062 |
+
st.rerun()
|
| 1063 |
+
|
| 1064 |
+
s = st.session_state.stats
|
| 1065 |
+
if s["total_files"] > 0:
|
| 1066 |
+
st.divider()
|
| 1067 |
+
st.markdown("### π Stats")
|
| 1068 |
+
st.metric("Files", s["total_files"])
|
| 1069 |
+
st.metric("Successful", s["successful"])
|
| 1070 |
+
if s["failed"]:
|
| 1071 |
+
st.metric("Failed", s["failed"], delta_color="inverse")
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1075 |
+
# MAIN CONTENT
|
| 1076 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1077 |
+
|
| 1078 |
+
import hashlib
|
| 1079 |
+
import io
|
| 1080 |
+
import time
|
| 1081 |
+
import zipfile
|
| 1082 |
+
from datetime import datetime
|
| 1083 |
+
from pathlib import Path
|
| 1084 |
+
from typing import Dict, Tuple
|
| 1085 |
+
|
| 1086 |
+
import streamlit as st
|
| 1087 |
+
|
| 1088 |
+
# All necessary components are already defined in this file
|
| 1089 |
+
# No relative imports needed
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
st.markdown("""
|
| 1093 |
+
<div class="pc-hero">
|
| 1094 |
+
<h1> PyStreamlit Converter Pro</h1>
|
| 1095 |
+
<p>Transform <strong>Jupyter Notebooks</strong> & <strong>Python scripts</strong>
|
| 1096 |
+
into polished, interactive <strong>Streamlit apps</strong> β in seconds.</p>
|
| 1097 |
+
<div>
|
| 1098 |
+
<span class="pc-badge">β¨ AST + Regex engine</span>
|
| 1099 |
+
<span class="pc-badge pc-badge-green">π¦ Batch & ZIP</span>
|
| 1100 |
+
<span class="pc-badge pc-badge-purple">π Deep Code Analysis</span>
|
| 1101 |
+
<span class="pc-badge pc-badge-amber">π Diff Viewer</span>
|
| 1102 |
+
<span class="pc-badge">β‘ Auto Caching</span>
|
| 1103 |
+
<span class="pc-badge pc-badge-green">π‘ Widget Suggester</span>
|
| 1104 |
+
</div>
|
| 1105 |
+
</div>
|
| 1106 |
+
""", unsafe_allow_html=True)
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
tab_convert, tab_analyze, tab_diff, tab_history, tab_dashboard, tab_help = st.tabs([
|
| 1110 |
+
"π Convert", "π Analyze", "π Diff", "π History", "π Dashboard", "π Help",
|
| 1111 |
+
])
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1115 |
+
# TAB 1 β CONVERT
|
| 1116 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1117 |
+
with tab_convert:
|
| 1118 |
+
if st.session_state.uploaded_files:
|
| 1119 |
+
ufs = st.session_state.uploaded_files
|
| 1120 |
+
st.markdown(f"### Processing **{len(ufs)}** file(s)")
|
| 1121 |
+
|
| 1122 |
+
for idx, uf in enumerate(ufs):
|
| 1123 |
+
raw = uf.getvalue()
|
| 1124 |
+
ext = Path(uf.name).suffix.upper()
|
| 1125 |
+
st.markdown('<div class="pc-card">', unsafe_allow_html=True)
|
| 1126 |
+
|
| 1127 |
+
hc1, hc2, hc3, hc4 = st.columns([4, 1, 1, 1])
|
| 1128 |
+
with hc1:
|
| 1129 |
+
st.markdown(f"#### π `{uf.name}`")
|
| 1130 |
+
st.caption(f"{len(raw)/1024:.1f} KB Β· {ext[1:]}")
|
| 1131 |
+
with hc2: badge(ext, "green")
|
| 1132 |
+
with hc3: badge(st.session_state.conversion_mode.split()[0], "purple")
|
| 1133 |
+
with hc4: badge("Ready")
|
| 1134 |
+
|
| 1135 |
+
try:
|
| 1136 |
+
with st.spinner(f"Converting `{uf.name}`β¦"):
|
| 1137 |
+
t0 = time.time()
|
| 1138 |
+
converted, original, report = _process_uploaded(uf)
|
| 1139 |
+
elapsed = time.time() - t0
|
| 1140 |
+
|
| 1141 |
+
s = st.session_state.stats
|
| 1142 |
+
s["total_files"] += 1
|
| 1143 |
+
s["successful"] += 1
|
| 1144 |
+
s["total_transformations"] += sum(1 for r in report if "β
" in r)
|
| 1145 |
+
|
| 1146 |
+
st.session_state.conversion_history.append({
|
| 1147 |
+
"filename": uf.name,
|
| 1148 |
+
"timestamp": datetime.now().strftime("%H:%M:%S"),
|
| 1149 |
+
"elapsed": f"{elapsed:.2f}s",
|
| 1150 |
+
"transformations": sum(1 for r in report if "β
" in r),
|
| 1151 |
+
"lines_in": len(original.splitlines()),
|
| 1152 |
+
"lines_out": len(converted.splitlines()),
|
| 1153 |
+
"status": "ok",
|
| 1154 |
+
})
|
| 1155 |
+
|
| 1156 |
+
st.success(f"β
Done in **{elapsed:.2f}s** β "
|
| 1157 |
+
f"{len(original.splitlines())} β {len(converted.splitlines())} lines, "
|
| 1158 |
+
f"{sum(1 for r in report if 'β
' in r)} transformations")
|
| 1159 |
+
|
| 1160 |
+
view = st.radio(
|
| 1161 |
+
"View", ["π Side-by-Side", "π Original", "β¨ Converted"],
|
| 1162 |
+
horizontal=True, key=f"view_{idx}_{uf.name}",
|
| 1163 |
+
)
|
| 1164 |
+
lim = 25_000
|
| 1165 |
+
if "Side-by-Side" in view:
|
| 1166 |
+
ca, cb = st.columns(2)
|
| 1167 |
+
with ca:
|
| 1168 |
+
st.markdown("##### π Original Code")
|
| 1169 |
+
st.code(original[:lim] + ("β¦" if len(original) > lim else ""),
|
| 1170 |
+
language="python", line_numbers=True)
|
| 1171 |
+
with cb:
|
| 1172 |
+
st.markdown("##### β¨ Converted")
|
| 1173 |
+
st.code(converted[:lim] + ("β¦" if len(converted) > lim else ""),
|
| 1174 |
+
language="python", line_numbers=True)
|
| 1175 |
+
elif "Original" in view:
|
| 1176 |
+
st.code(original[:lim*2], language="python", line_numbers=True)
|
| 1177 |
+
else:
|
| 1178 |
+
st.code(converted[:lim*2], language="python", line_numbers=True)
|
| 1179 |
+
|
| 1180 |
+
m1, m2, m3, m4, m5 = st.columns(5)
|
| 1181 |
+
with m1: st.metric("Original", f"{len(original):,}", "chars")
|
| 1182 |
+
with m2: st.metric("Converted", f"{len(converted):,}", "chars")
|
| 1183 |
+
with m3: st.metric("Delta", f"{len(converted)-len(original):+,}", "chars")
|
| 1184 |
+
with m4: st.metric("Transforms", sum(1 for r in report if "β
" in r))
|
| 1185 |
+
with m5: st.metric("Time", f"{elapsed:.2f}s")
|
| 1186 |
+
|
| 1187 |
+
dl_col, rep_col = st.columns(2)
|
| 1188 |
+
with dl_col:
|
| 1189 |
+
st.download_button(
|
| 1190 |
+
f"β¬οΈ Download `{Path(uf.name).stem}_streamlit.py`",
|
| 1191 |
+
converted,
|
| 1192 |
+
file_name=f"{Path(uf.name).stem}_streamlit.py",
|
| 1193 |
+
mime="text/plain",
|
| 1194 |
+
key=f"dl_{idx}_{uf.name}",
|
| 1195 |
+
use_container_width=True,
|
| 1196 |
+
type="primary",
|
| 1197 |
+
)
|
| 1198 |
+
with rep_col:
|
| 1199 |
+
with st.expander("π Conversion Report"):
|
| 1200 |
+
render_report(report)
|
| 1201 |
+
|
| 1202 |
+
except Exception as exc:
|
| 1203 |
+
s = st.session_state.stats
|
| 1204 |
+
s["total_files"] += 1
|
| 1205 |
+
s["failed"] += 1
|
| 1206 |
+
st.session_state.conversion_history.append({
|
| 1207 |
+
"filename": uf.name,
|
| 1208 |
+
"timestamp": datetime.now().strftime("%H:%M:%S"),
|
| 1209 |
+
"status": "err", "error": str(exc),
|
| 1210 |
+
})
|
| 1211 |
+
st.error(f"β {exc}")
|
| 1212 |
+
with st.expander("π Traceback"):
|
| 1213 |
+
st.exception(exc)
|
| 1214 |
+
|
| 1215 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 1216 |
+
if idx < len(ufs) - 1:
|
| 1217 |
+
st.divider()
|
| 1218 |
+
|
| 1219 |
+
elif st.session_state.uploaded_zip:
|
| 1220 |
+
st.markdown("### π¦ Batch ZIP Processing")
|
| 1221 |
+
try:
|
| 1222 |
+
results: Dict[str, Tuple] = {}
|
| 1223 |
+
with zipfile.ZipFile(st.session_state.uploaded_zip) as zr:
|
| 1224 |
+
py_files = [f for f in zr.namelist() if f.endswith((".py", ".ipynb"))]
|
| 1225 |
+
|
| 1226 |
+
if not py_files:
|
| 1227 |
+
st.warning("No .py or .ipynb files in the ZIP.")
|
| 1228 |
+
else:
|
| 1229 |
+
prog = st.progress(0)
|
| 1230 |
+
status_ph = st.empty()
|
| 1231 |
+
for i, fname in enumerate(py_files):
|
| 1232 |
+
status_ph.markdown(f"**{i+1}/{len(py_files)}** β `{fname}`")
|
| 1233 |
+
with zipfile.ZipFile(st.session_state.uploaded_zip) as zr:
|
| 1234 |
+
raw = zr.read(fname)
|
| 1235 |
+
buf = io.BytesIO(raw); buf.name = fname
|
| 1236 |
+
try:
|
| 1237 |
+
conv, orig, rep = _process_uploaded(buf)
|
| 1238 |
+
results[fname] = (conv, orig, rep, None)
|
| 1239 |
+
st.session_state.stats["successful"] += 1
|
| 1240 |
+
except Exception as exc:
|
| 1241 |
+
results[fname] = (f"# Error: {exc}", "", [f"β {exc}"], str(exc))
|
| 1242 |
+
st.session_state.stats["failed"] += 1
|
| 1243 |
+
st.session_state.stats["total_files"] += 1
|
| 1244 |
+
prog.progress((i + 1) / len(py_files))
|
| 1245 |
+
|
| 1246 |
+
status_ph.empty(); prog.empty()
|
| 1247 |
+
ok = sum(1 for v in results.values() if v[3] is None)
|
| 1248 |
+
st.success(f"β
Converted **{ok}/{len(py_files)}** files")
|
| 1249 |
+
|
| 1250 |
+
out_zip = io.BytesIO()
|
| 1251 |
+
with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as ozf:
|
| 1252 |
+
for fname, (conv, _, _, err) in results.items():
|
| 1253 |
+
if err is None:
|
| 1254 |
+
ozf.writestr(f"{Path(fname).stem}_streamlit.py", conv)
|
| 1255 |
+
st.download_button(
|
| 1256 |
+
"β¬οΈ Download All (ZIP)",
|
| 1257 |
+
out_zip.getvalue(),
|
| 1258 |
+
"streamlit_converted_apps.zip",
|
| 1259 |
+
"application/zip",
|
| 1260 |
+
use_container_width=True, type="primary",
|
| 1261 |
+
)
|
| 1262 |
+
|
| 1263 |
+
for fname, (conv, orig, rep, err) in results.items():
|
| 1264 |
+
with st.expander(f"{'β
' if err is None else 'β'} {fname}"):
|
| 1265 |
+
if err:
|
| 1266 |
+
st.error(err)
|
| 1267 |
+
else:
|
| 1268 |
+
ca2, cb2 = st.columns(2)
|
| 1269 |
+
with ca2:
|
| 1270 |
+
st.markdown("**Original**")
|
| 1271 |
+
st.code(orig[:5000], language="python")
|
| 1272 |
+
with cb2:
|
| 1273 |
+
st.markdown("**Converted**")
|
| 1274 |
+
st.code(conv[:5000], language="python")
|
| 1275 |
+
with st.expander("Report"):
|
| 1276 |
+
render_report(rep)
|
| 1277 |
+
except Exception as exc:
|
| 1278 |
+
st.error(f"ZIP failed: {exc}")
|
| 1279 |
+
st.exception(exc)
|
| 1280 |
+
|
| 1281 |
+
else:
|
| 1282 |
+
st.info("π Upload files or try a sample notebook/script using the sidebar.")
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1286 |
+
# TAB 2 β ANALYZE
|
| 1287 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1288 |
+
with tab_analyze:
|
| 1289 |
+
st.markdown("### π Deep Code Analysis")
|
| 1290 |
+
|
| 1291 |
+
if st.session_state.uploaded_files:
|
| 1292 |
+
names = [uf.name for uf in st.session_state.uploaded_files]
|
| 1293 |
+
sel = st.selectbox("Select file", names)
|
| 1294 |
+
uf = next(f for f in st.session_state.uploaded_files if f.name == sel)
|
| 1295 |
+
try:
|
| 1296 |
+
ext = Path(uf.name).suffix.lower()
|
| 1297 |
+
raw = uf.getvalue()
|
| 1298 |
+
src = extract_notebook(raw) if ext == ".ipynb" else raw.decode("utf-8")
|
| 1299 |
+
render_analysis(CodeAnalyzer(src), uf.name)
|
| 1300 |
+
except Exception as exc:
|
| 1301 |
+
st.error(f"Analysis failed: {exc}")
|
| 1302 |
+
else:
|
| 1303 |
+
st.info("Upload files to run analysis.")
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1307 |
+
# TAB 3 β DIFF
|
| 1308 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1309 |
+
with tab_diff:
|
| 1310 |
+
st.markdown("### π Diff Viewer")
|
| 1311 |
+
st.caption("Line-by-line comparison: original vs converted code.")
|
| 1312 |
+
|
| 1313 |
+
if st.session_state.uploaded_files:
|
| 1314 |
+
names = [uf.name for uf in st.session_state.uploaded_files]
|
| 1315 |
+
sel = st.selectbox("File to diff", names, key="diff_sel")
|
| 1316 |
+
uf = next(f for f in st.session_state.uploaded_files if f.name == sel)
|
| 1317 |
+
ctx = st.slider("Context lines", 1, 10, 4)
|
| 1318 |
+
|
| 1319 |
+
try:
|
| 1320 |
+
converted, original, _ = _process_uploaded(uf)
|
| 1321 |
+
diff_html = build_diff_html(original, converted, ctx)
|
| 1322 |
+
dc1, dc2 = st.columns(2)
|
| 1323 |
+
with dc1: st.metric("Lines added", diff_html.count('class="diff-add"'))
|
| 1324 |
+
with dc2: st.metric("Lines removed", diff_html.count('class="diff-rem"'))
|
| 1325 |
+
st.markdown(diff_html, unsafe_allow_html=True)
|
| 1326 |
+
except Exception as exc:
|
| 1327 |
+
st.error(f"Diff failed: {exc}")
|
| 1328 |
+
else:
|
| 1329 |
+
st.info("Upload a file to see the diff.")
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1333 |
+
# TAB 4 β HISTORY
|
| 1334 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1335 |
+
with tab_history:
|
| 1336 |
+
st.markdown("### π Conversion History")
|
| 1337 |
+
hist = st.session_state.conversion_history
|
| 1338 |
+
|
| 1339 |
+
if hist:
|
| 1340 |
+
if st.button("ποΈ Clear History"):
|
| 1341 |
+
st.session_state.conversion_history = []
|
| 1342 |
+
st.rerun()
|
| 1343 |
+
for entry in reversed(hist):
|
| 1344 |
+
ok = entry.get("status") == "ok"
|
| 1345 |
+
icon = "β
" if ok else "β"
|
| 1346 |
+
extra = (
|
| 1347 |
+
f" Β· {entry.get('lines_in','?')} β {entry.get('lines_out','?')} lines"
|
| 1348 |
+
f" Β· {entry.get('transformations',0)} transforms Β· β± {entry.get('elapsed','β')}"
|
| 1349 |
+
) if ok else f" Β· {entry.get('error','')}"
|
| 1350 |
+
st.markdown(
|
| 1351 |
+
f'<div class="timeline-item {"ok" if ok else "err"}">'
|
| 1352 |
+
f'<strong>{icon} {entry["filename"]}</strong>'
|
| 1353 |
+
f'<span style="font-size:.8em;opacity:.6;margin-left:8px">{entry["timestamp"]}</span>'
|
| 1354 |
+
f'<div style="font-size:.82em;opacity:.7">{extra}</div></div>',
|
| 1355 |
+
unsafe_allow_html=True,
|
| 1356 |
+
)
|
| 1357 |
+
else:
|
| 1358 |
+
st.info("No conversions yet this session.")
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1362 |
+
# TAB 5 β DASHBOARD
|
| 1363 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1364 |
+
with tab_dashboard:
|
| 1365 |
+
st.markdown("### π Session Dashboard")
|
| 1366 |
+
s = st.session_state.stats
|
| 1367 |
+
|
| 1368 |
+
if s["total_files"] > 0:
|
| 1369 |
+
dc1, dc2, dc3, dc4 = st.columns(4)
|
| 1370 |
+
with dc1: metric_card("Total Files", str(s["total_files"]), "π")
|
| 1371 |
+
with dc2: metric_card("Successful", str(s["successful"]), "β
")
|
| 1372 |
+
with dc3: metric_card("Failed", str(s["failed"]), "β")
|
| 1373 |
+
with dc4: metric_card("Transforms", str(s["total_transformations"]), "β‘")
|
| 1374 |
+
|
| 1375 |
+
st.markdown("")
|
| 1376 |
+
rate = s["successful"] / s["total_files"] * 100
|
| 1377 |
+
st.markdown(f"**Success rate: {rate:.0f}%**")
|
| 1378 |
+
st.markdown(
|
| 1379 |
+
f'<div class="health-bar-bg">'
|
| 1380 |
+
f'<div class="health-bar-fg" style="width:{rate}%"></div></div>',
|
| 1381 |
+
unsafe_allow_html=True,
|
| 1382 |
+
)
|
| 1383 |
+
|
| 1384 |
+
hist = st.session_state.conversion_history
|
| 1385 |
+
if hist:
|
| 1386 |
+
st.markdown("")
|
| 1387 |
+
st.markdown("**Recent conversions**")
|
| 1388 |
+
st.dataframe(
|
| 1389 |
+
[{"File": h["filename"], "Time": h["timestamp"],
|
| 1390 |
+
"Status": "β
" if h.get("status") == "ok" else "β",
|
| 1391 |
+
"Lines in": h.get("lines_in", "β"), "Lines out": h.get("lines_out", "β"),
|
| 1392 |
+
"Transforms": h.get("transformations", "β"), "Duration": h.get("elapsed", "β")}
|
| 1393 |
+
for h in reversed(hist)],
|
| 1394 |
+
use_container_width=True, hide_index=True,
|
| 1395 |
+
)
|
| 1396 |
+
else:
|
| 1397 |
+
st.info("No conversions yet.")
|
| 1398 |
+
|
| 1399 |
+
|
| 1400 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1401 |
+
# TAB 6 β HELP
|
| 1402 |
+
# ββββββββββββββββββββββββββββββββββββββ
|
| 1403 |
+
with tab_help:
|
| 1404 |
+
st.markdown("### π How It Works")
|
| 1405 |
+
ca, cb = st.columns(2)
|
| 1406 |
+
|
| 1407 |
+
with ca:
|
| 1408 |
+
st.markdown("""
|
| 1409 |
+
**π§ Conversion Strategies**
|
| 1410 |
+
|
| 1411 |
+
| Strategy | Best For |
|
| 1412 |
+
|---|---|
|
| 1413 |
+
| **Hybrid** (default) | Any file β AST + regex |
|
| 1414 |
+
| **AST Precise** | Clean Python 3.9+ |
|
| 1415 |
+
| **Regex Fast** | Large / syntax-heavy files |
|
| 1416 |
+
|
| 1417 |
+
**π Transformation Map**
|
| 1418 |
+
|
| 1419 |
+
| Original | Streamlit |
|
| 1420 |
+
|---|---|
|
| 1421 |
+
| `print(x)` | `st.write(x)` |
|
| 1422 |
+
| `display(df)` | `st.dataframe(df)` |
|
| 1423 |
+
| `df.head()` | `st.dataframe(df.head())` |
|
| 1424 |
+
| `df.describe()` | `st.dataframe(df.describe())` |
|
| 1425 |
+
| `plt.show()` | `st.pyplot(plt.gcf())` |
|
| 1426 |
+
| `fig.show()` | `st.plotly_chart(fig)` |
|
| 1427 |
+
| `show(bokeh_fig)` | `st.bokeh_chart(fig)` |
|
| 1428 |
+
| Notebook markdown | `st.markdown(...)` |
|
| 1429 |
+
| `%magic` / `!shell` | *(removed)* |
|
| 1430 |
+
| `load_*(...)` fn | `@st.cache_data` added |
|
| 1431 |
+
""")
|
| 1432 |
+
|
| 1433 |
+
with cb:
|
| 1434 |
+
st.markdown("""
|
| 1435 |
+
**β¨ Advanced Features**
|
| 1436 |
+
|
| 1437 |
+
- **@st.cache_data auto-injection** β functions named `load_*`, `fetch_*`, `read_*`, `get_data_*` get cached automatically
|
| 1438 |
+
- **Widget suggester** β scans hard-coded literals and proposes sidebar sliders, checkboxes, and text inputs
|
| 1439 |
+
- **Error handling wrapper** β wraps the app body in `try/except` with `st.error()` + collapsible traceback
|
| 1440 |
+
- **Diff viewer** β unified-diff comparison with configurable context lines
|
| 1441 |
+
- **Deep code analysis** β complexity metrics, library detection, function inventory
|
| 1442 |
+
- **Batch ZIP processing** β convert an entire folder, download all results as ZIP
|
| 1443 |
+
- **Session history timeline** β timestamped record of every conversion
|
| 1444 |
+
- **Light / Dark theme** β toggle from the sidebar
|
| 1445 |
+
|
| 1446 |
+
**π‘ Tips**
|
| 1447 |
+
|
| 1448 |
+
1. Use the **π Analyze** tab first to preview what will change
|
| 1449 |
+
2. Enable **Auto sidebar widgets** to make hard-coded parameters interactive
|
| 1450 |
+
3. **Hybrid** mode handles 99 % of notebooks and scripts reliably
|
| 1451 |
+
4. The **Diff viewer** is great for code review before deploying
|
| 1452 |
+
""")
|
| 1453 |
+
|
| 1454 |
+
st.info("π‘ Run the **Analyzer** before converting to see suggestions, then convert "
|
| 1455 |
+
"with **Auto Sidebar Widgets** enabled for a fully interactive app.")
|
| 1456 |
+
|
| 1457 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1458 |
+
# CONVERTER CORE
|
| 1459 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1460 |
+
|
| 1461 |
+
class CodeAnalyzer:
|
| 1462 |
+
def get_unique_report(self):
|
| 1463 |
+
seen = set()
|
| 1464 |
+
unique_report = []
|
| 1465 |
+
for item in self.conversion_report:
|
| 1466 |
+
if item not in seen:
|
| 1467 |
+
seen.add(item)
|
| 1468 |
+
unique_report.append(item)
|
| 1469 |
+
return unique_report
|
| 1470 |
+
|
| 1471 |
+
|
| 1472 |
+
# ==============================
|
| 1473 |
+
# NOTEBOOK PROCESSING
|
| 1474 |
+
# ==============================
|
| 1475 |
+
|
| 1476 |
+
def extract_code_from_notebook(notebook_content: str, preserve_markdown: bool = True) -> str:
|
| 1477 |
+
"""Convert notebook to Python script with enhanced markdown handling."""
|
| 1478 |
+
try:
|
| 1479 |
+
nb = nbformat.reads(notebook_content, as_version=4)
|
| 1480 |
+
except Exception as e:
|
| 1481 |
+
raise ValueError(f"Invalid notebook format: {e}")
|
| 1482 |
+
|
| 1483 |
+
lines = []
|
| 1484 |
+
cell_num = 0
|
| 1485 |
+
|
| 1486 |
+
for cell in nb.cells:
|
| 1487 |
+
cell_num += 1
|
| 1488 |
+
|
| 1489 |
+
if cell.cell_type == "markdown" and preserve_markdown:
|
| 1490 |
+
md_content = cell.source
|
| 1491 |
+
lines.append(f"\n# {'='*60}")
|
| 1492 |
+
lines.append(f"# MARKDOWN CELL {cell_num}")
|
| 1493 |
+
lines.append(f"# {'='*60}")
|
| 1494 |
+
|
| 1495 |
+
for md_line in md_content.split('\n'):
|
| 1496 |
+
if not md_line.strip():
|
| 1497 |
+
lines.append("#")
|
| 1498 |
+
else:
|
| 1499 |
+
clean_line = md_line.replace('"""', "'''").replace("'''", '"""')
|
| 1500 |
+
if md_line.strip().startswith('#'):
|
| 1501 |
+
lines.append(f"# {clean_line}")
|
| 1502 |
+
else:
|
| 1503 |
+
lines.append(f"# {clean_line}")
|
| 1504 |
+
lines.append("")
|
| 1505 |
+
|
| 1506 |
+
elif cell.cell_type == "code":
|
| 1507 |
+
code_content = cell.source
|
| 1508 |
+
|
| 1509 |
+
if lines and lines[-1].strip():
|
| 1510 |
+
lines.append("")
|
| 1511 |
+
|
| 1512 |
+
if hasattr(cell, 'metadata') and cell.metadata:
|
| 1513 |
+
lines.append(f"# Cell {cell_num} metadata: {cell.metadata}")
|
| 1514 |
+
|
| 1515 |
+
lines.append(code_content)
|
| 1516 |
+
|
| 1517 |
+
if not code_content.endswith('\n'):
|
| 1518 |
+
lines.append("")
|
| 1519 |
+
|
| 1520 |
+
result = "\n".join(lines)
|
| 1521 |
+
if not result.endswith('\n'):
|
| 1522 |
+
result += "\n"
|
| 1523 |
+
|
| 1524 |
+
return result
|
| 1525 |
+
|
| 1526 |
+
|
| 1527 |
+
# ==============================
|
| 1528 |
+
# FILE PROCESSING UTILITIES
|
| 1529 |
+
# ==============================
|
| 1530 |
+
|
| 1531 |
+
@st.cache_data(show_spinner=False)
|
| 1532 |
+
def process_single_file_cached(file_bytes: bytes, filename: str, file_hash: str,
|
| 1533 |
+
conversion_mode: str, large_file_threshold: int,
|
| 1534 |
+
add_main_guard: bool, preserve_comments: bool):
|
| 1535 |
+
"""Cached file processing function."""
|
| 1536 |
+
file_extension = Path(filename).suffix.lower()
|
| 1537 |
+
|
| 1538 |
+
try:
|
| 1539 |
+
if file_extension == ".ipynb":
|
| 1540 |
+
original_code = extract_code_from_notebook(file_bytes.decode('utf-8'),
|
| 1541 |
+
preserve_markdown=preserve_comments)
|
| 1542 |
+
else:
|
| 1543 |
+
original_code = file_bytes.decode("utf-8")
|
| 1544 |
+
|
| 1545 |
+
converter = HybridConverter(
|
| 1546 |
+
original_code,
|
| 1547 |
+
filename,
|
| 1548 |
+
conversion_mode=conversion_mode,
|
| 1549 |
+
large_file_threshold=large_file_threshold,
|
| 1550 |
+
add_main_guard=add_main_guard,
|
| 1551 |
+
preserve_comments=preserve_comments
|
| 1552 |
+
)
|
| 1553 |
+
streamlit_code = converter.convert()
|
| 1554 |
+
|
| 1555 |
+
return streamlit_code, original_code, converter.get_conversion_report()
|
| 1556 |
+
|
| 1557 |
+
except Exception as e:
|
| 1558 |
+
error_msg = f"Error processing {filename}: {str(e)}"
|
| 1559 |
+
return f"# {error_msg}\n# Original file could not be processed.", "", [f"β {error_msg}"]
|
| 1560 |
+
|
| 1561 |
+
def process_single_file(uploaded_file, **kwargs):
|
| 1562 |
+
"""Process a single uploaded file."""
|
| 1563 |
+
file_bytes = uploaded_file.getvalue()
|
| 1564 |
+
file_hash = hashlib.md5(file_bytes).hexdigest()[:8]
|
| 1565 |
+
return process_single_file_cached(
|
| 1566 |
+
file_bytes, uploaded_file.name, file_hash, **kwargs
|
| 1567 |
+
)
|
| 1568 |
+
|
img_1.png
ADDED
|
Git LFS Details
|
img_2.png
ADDED
|
img_3.png
ADDED
|
Git LFS Details
|