Jack-ki1's picture
Update README.md
3d5a2a0 verified
---
license: mit
title: python_to_streamlit_convertor
sdk: streamlit
emoji: πŸ“Š
colorFrom: green
colorTo: gray
sdk_version: 1.51.0
---
# Python β†’ Streamlit Converter Pro
A powerful, production-ready tool that converts Python scripts and Jupyter Notebooks into fully functional Streamlit applications. Handles large files, preserves comments and markdown, and provides multiple conversion strategies.
## ✨ Features
### Core Capabilities
- **Multi-Format Support**: Convert `.py` files and `.ipynb` notebooks
- **Large File Handling**: Efficiently processes files up to 5MB+ with optimized algorithms
- **Comment Preservation**: All comments, docstrings, and inline documentation are preserved
- **Markdown Support**: Notebook markdown cells are converted to commented Python code
- **Batch Processing**: Upload ZIP archives to convert multiple files at once
### Conversion Strategies
1. **Hybrid Mode (Recommended)**: Combines AST parsing with regex patterns
- Best balance of accuracy and performance
- Handles complex code structures
- Preserves formatting and comments
2. **AST Mode (Precise)**: Pure abstract syntax tree transformation
- Deep understanding of code structure
- Best for complex transformations
- Preserves all code semantics
3. **Regex Mode (Fast)**: Pattern-based matching
- Fastest for very large files
- Good for simple conversions
- Efficient memory usage
4. **Auto Mode**: Automatically selects the best strategy based on file size
### What Gets Converted?
| Original Code | Streamlit Equivalent |
|--------------|---------------------|
| `print(x)` | `st.write(x)` |
| `display(df)` | `st.dataframe(df)` |
| `df.head()` / `df.tail()` | `st.dataframe(df.head())` |
| `plt.show()` | `st.pyplot(plt.gcf())` |
| `fig.show()` (Plotly) | `st.plotly_chart(fig)` |
| Markdown cells | Commented markdown |
| All comments | Preserved |
## πŸš€ Installation
1. Clone or download this repository
2. Install dependencies:
```bash
pip install -r Requirements.txt
```
## πŸ“– Usage
### Running the Application
```bash
streamlit run app.py
```
The application will open in your default web browser.
### Basic Workflow
1. **Upload Files**: Use the sidebar to upload Python files or Jupyter notebooks
- Individual files: Upload one or more files directly
- ZIP archive: Upload a ZIP containing multiple files
2. **Configure Settings** (Optional):
- Choose conversion strategy (Hybrid recommended)
- Set large file threshold
- Enable/disable main guard
- Toggle comment preservation
3. **Review & Download**:
- View original and converted code side-by-side
- Check conversion report for details
- Download the converted Streamlit app
### Advanced Settings
- **Conversion Strategy**: Choose how the code is analyzed and converted
- **Large File Threshold**: Files above this size (in KB) use optimized processing
- **Main Guard**: Adds `if __name__ == '__main__':` wrapper for safer execution
- **Preserve Comments**: Keep all comments and docstrings in the output
## 🎯 Use Cases
- **Data Science Projects**: Convert Jupyter notebooks with visualizations to interactive Streamlit dashboards
- **Script Migration**: Transform existing Python scripts into web applications
- **Batch Conversion**: Process entire project folders at once
- **Prototyping**: Quickly create Streamlit apps from existing code
## πŸ”§ Technical Details
### Architecture
- **AST-Based Transformation**: Uses Python's `ast` module for structural analysis
- **Regex Fallback**: Pattern matching for edge cases and large files
- **Hybrid Approach**: Combines both methods for optimal results
- **Error Recovery**: Graceful fallbacks when parsing fails
### Performance
- Handles files up to 5MB+ efficiently
- Chunked processing for large files
- Caching for repeated conversions
- Memory-efficient algorithms
### Limitations
- Does not execute code (safe conversion only)
- Complex interactive widgets (e.g., `ipywidgets`) require manual conversion
- Some edge cases in very complex code may need manual adjustment
- Manual review recommended before production deployment
## πŸ“ Example
### Input (Jupyter Notebook Cell):
```python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
print(f"Dataset has {len(df)} rows")
display(df.head())
plt.figure(figsize=(10, 6))
plt.plot(df['x'], df['y'])
plt.show()
```
### Output (Streamlit App):
```python
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
st.set_page_config(
page_title='Converted App',
layout='wide'
)
st.title(' Converted Streamlit App')
df = pd.read_csv('data.csv')
st.write(f"Dataset has {len(df)} rows")
st.dataframe(df.head())
plt.figure(figsize=(10, 6))
plt.plot(df['x'], df['y'])
st.pyplot(plt.gcf())
```
## πŸ› οΈ Development
### Project Structure
```
python_to_full_streamlit/
β”œβ”€β”€ app.py # Main Streamlit application
β”œβ”€β”€ Requirements.txt # Python dependencies
└── README.md # This file
```
### Key Components
1. **HybridConverter**: Main conversion engine with multiple strategies
2. **CommentPreservingTransformer**: AST transformer that preserves code structure
3. **extract_code_from_notebook**: Enhanced notebook processing with markdown support
4. **File Processing**: Cached, efficient file handling with error recovery
## 🀝 Contributing
This is a production-ready converter. Improvements welcome for:
- Additional conversion patterns
- Performance optimizations
- Edge case handling
- UI/UX enhancements
## πŸ“„ License
This project is provided as-is for converting Python code to Streamlit applications.
## πŸ’‘ Tips
- Use **Hybrid mode** for best results on most files
- Enable **comment preservation** to maintain documentation
- For very large files (>1MB), consider using **Regex mode**
- Always review converted code before deployment
- Test the generated Streamlit app with sample data
## πŸ› Troubleshooting
**Issue**: Conversion fails on a file
- **Solution**: Try a different conversion mode (AST vs Regex)
- Check if the file has syntax errors
- Verify the file is valid Python/Jupyter format
**Issue**: Comments are missing
- **Solution**: Enable "Preserve Comments" in advanced settings
- Use AST or Hybrid mode instead of Regex
**Issue**: Large file processing is slow
- **Solution**: Increase the large file threshold
- Use Regex mode for very large files
- Process files individually instead of in ZIP
---
**Made with ❀️ for the Streamlit community**