requirements-installer


Namerequirements-installer JSON
Version 1.1.0 PyPI version JSON
download
home_pageNone
SummaryAutomatically detect and install Python dependencies from your code
upload_time2025-10-10 06:34:47
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT
keywords pip requirements dependencies automation installer
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Requirements Installer πŸš€

**Tired of hunting down missing Python dependencies?** Requirements Installer automatically detects and installs all third-party packages your Python script needsβ€”no `requirements.txt` needed!

Simply point it at your Python file, and it handles the rest. Perfect for running unfamiliar scripts, quick prototyping, or setting up development environments.

## 🎯 Two Ways to Use

### 1️⃣ Inside Your Code (Easiest!)
```python
from requirements_installer import auto_install
auto_install()
```

### 2️⃣ Command Line
```bash
requirements_installer --file mycode.py
```

---

## ✨ Features

- **⚑ Auto-Install Inside Code** - Just `from requirements_installer import auto_install; auto_install()` and you're done!
- **πŸ““ Jupyter/Colab Support** - Scans and installs from `.ipynb` files automatically
- **πŸ” Smart Import Detection** - Automatically scans your Python files for all third-party imports
- **πŸ“¦ One-Command Install** - Detects and installs dependencies in a single step
- **πŸ“ Generate requirements.txt** - Automatically create requirements.txt with pinned versions
- **🎯 Interactive Version Selection** - Optionally choose specific versions for each package
- **πŸ”’ Virtual Environment Support** - Create and install into isolated environments
- **🧠 Intelligent Filtering** - Excludes stdlib and local modules automatically
- **πŸ“„ Module-to-Package Mapping** - Handles 150+ tricky cases like `cv2` β†’ `opencv-python`, `pptx` β†’ `python-pptx`
- **πŸ”§ Easy to Extend** - Add new mappings by editing a simple JSON file
- **🌍 One-Hop Local Import Scanning** - Follows local imports to catch all dependencies
- **πŸ’ͺ Pure Python** - No external dependencies required

---

## πŸ”₯ Installation

```bash
pip install requirements_installer
```

Or install from source:

```bash
git clone https://github.com/FH-Prevail/requirements_installer.git
cd requirements_installer
pip install -e .
```

---

## πŸš€ Quick Start

### ⭐ NEW: Auto-Install Inside Your Code (Recommended!)

**The easiest way - just add 2 lines to your script:**

```python
from requirements_installer import auto_install
auto_install()

# Now use any packages - they'll be auto-installed if missing!
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
```

**Perfect for Jupyter/Colab notebooks:**

```python
# Cell 1: Your imports and code
import pandas as pd
import torch
from transformers import AutoModel
# ... your code ...

# Cell 2: Install everything (run this if imports fail)
!pip install -q requirements_installer
from requirements_installer import auto_install
auto_install()  # Scans all cells above and installs missing packages!

# Now re-run Cell 1 and it will work!
```

**Or install dependencies first:**

```python
# Cell 1: Setup (run first)
!pip install -q requirements_installer
from requirements_installer import auto_install
auto_install()  # If you have imports in other cells, it will find them

# Cell 2+: Your code with any imports
import torch
import transformers
```

### Basic Command-Line Usage

**After `pip install requirements_installer`, use it as a command:**

```bash
# Scan and install dependencies for a Python file
requirements_installer --file mycode.py

# Works with Jupyter notebooks too!
requirements_installer --file notebook.ipynb
```

### With Virtual Environment

```bash
# Create a venv and install dependencies there
requirements_installer --file mycode.py --use-venv --venv-path .venv
```

### Interactive Version Selection

```bash
# Choose specific versions for each package
requirements_installer --file mycode.py --ask-version
```

Example interaction:
```
==================================================
Version Selection
==================================================

Install latest version of 'numpy'? [Y/n]: n
Enter version for 'numpy' (e.g., 1.2.3): 1.24.0

Install latest version of 'pandas'? [Y/n]: y

Install latest version of 'requests'? [Y/n]: 
```

### Print Requirements Only

```bash
# Just show what would be installed, don't install
requirements_installer --file mycode.py --print-requirements
```

### Generate requirements.txt

```bash
# Install dependencies AND generate requirements.txt with pinned versions
requirements_installer --file mycode.py --generate-requirements
```

This creates a `requirements.txt` file like:
```
# Generated by requirements_installer
# Install with: pip install -r requirements.txt

beautifulsoup4==4.12.2
numpy==1.24.3
pandas==2.0.2
requests==2.31.0
```

You can specify a custom output path:
```bash
requirements_installer --file mycode.py --generate-requirements --requirements-path deps.txt
```

---

## πŸ“– Usage Examples

### Example 1: Auto-Install in Script (NEW! πŸŽ‰)
Make your scripts self-installing:

```python
# my_analysis.py
from requirements_installer import auto_install
auto_install()

# Now use any packages!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')
plt.plot(df['x'], df['y'])
plt.show()
```

**Just run it:**
```bash
python my_analysis.py  # Auto-installs pandas, numpy, matplotlib!
```

### Example 2: Jupyter/Colab Notebook

**Option A - Install before running (recommended):**
```python
# Cell 1: One-time setup
!pip install -q requirements_installer
from requirements_installer import auto_install
auto_install()  # Scans ALL cells in notebook (even unexecuted ones!)

# Cell 2+: Now run your code
import pandas as pd
import torch
from transformers import AutoModel
model = AutoModel.from_pretrained('bert-base-uncased')
```

**Option B - Fix import errors after they happen:**
```python
# Cell 1: Try to run your code
import pandas as pd
import torch
# ImportError: No module named 'torch'

# Cell 2: Install missing dependencies
!pip install -q requirements_installer
from requirements_installer import auto_install
auto_install()  # Scans ALL cells and installs what's needed!

# Cell 3: Re-run Cell 1 - now it works!
```

**How it works in Colab/Jupyter:**
- Automatically finds and reads your notebook file
- Scans **ALL cells** (even unexecuted ones!)
- Installs missing packages automatically
- No need to execute cells first - just call `auto_install()`

### Example 3: Quick Script Setup
You clone a repo without a `requirements.txt`:

```bash
requirements_installer --file app.py
```

Output:
```
Detected environment: current Python at /usr/bin/python3
Entry file: /home/user/project/app.py
Installing: numpy pandas requests

==================================================
Installation Summary
==================================================
Installed: numpy, pandas, requests
Already satisfied: (none)
All requested packages are now present.
```

### Example 4: Isolated Development Environment

```bash
requirements_installer --file main.py --use-venv
```

Creates a `.venv` folder and installs all dependencies there, keeping your system Python clean.

### Example 5: Precise Version Control

```bash
requirements_installer --file analysis.py --ask-version
```

Prompts you for each package, letting you pin versions for reproducibility.

### Example 6: Generate requirements.txt for Team Sharing

You inherit a script without documentation:

```bash
requirements_installer --file data_pipeline.py --generate-requirements
```

Output:
```
Detected environment: current Python at /usr/bin/python3
Entry file: /home/user/project/data_pipeline.py
Installing: pandas numpy sqlalchemy psycopg2-binary

==================================================
Installation Summary
==================================================
Installed: pandas, numpy, sqlalchemy, psycopg2-binary
Already satisfied: (none)
All requested packages are now present.

πŸ“ Generating requirements.txt...
βœ… Generated requirements.txt with 4 packages

You can now install these dependencies with:
  pip install -r requirements.txt
```

The generated `requirements.txt`:
```
# Generated by requirements_installer
# Install with: pip install -r requirements.txt

numpy==1.24.3
pandas==2.0.2
psycopg2-binary==2.9.6
sqlalchemy==2.0.15
```

Now you can share this with your team for reproducible installations!

---

## πŸ”§ Command-Line Options

**After installation, use the `requirements_installer` command:**

```
usage: requirements_installer [-h] --file FILE [--use-venv] 
                              [--venv-path VENV_PATH]
                              [--print-requirements] [--ask-version]
                              [--generate-requirements]
                              [--requirements-path REQUIREMENTS_PATH]

options:
  -h, --help            Show this help message and exit
  --file FILE           Entry Python file or Jupyter notebook (.ipynb) to scan
  --use-venv            Create and use a virtual environment
  --venv-path VENV_PATH 
                        Where to create the venv (default: .venv)
  --print-requirements  Only print inferred packages and exit
  --ask-version         Interactively ask for version preference for each package
  --generate-requirements
                        Generate requirements.txt with pinned versions after installation
  --requirements-path REQUIREMENTS_PATH
                        Path for requirements.txt file (default: requirements.txt)
```

**Examples:**
```bash
# Basic usage
requirements_installer --file mycode.py

# With virtual environment
requirements_installer --file mycode.py --use-venv

# Interactive version selection
requirements_installer --file mycode.py --ask-version

# Scan Jupyter notebook
requirements_installer --file notebook.ipynb

# Generate requirements.txt
requirements_installer --file mycode.py --generate-requirements

# Custom requirements file path
requirements_installer --file mycode.py --generate-requirements --requirements-path deps.txt
```

**Note:** If you cloned the repository and want to run directly without installation:
```bash
python requirements_installer.py --file mycode.py
```

## 🐍 Python API

```python
from requirements_installer import auto_install

# Auto-detect and install (recommended)
auto_install()

# Specify file explicitly
auto_install(file_path='script.py')
auto_install(file_path='notebook.ipynb')

# Use virtual environment
auto_install(use_venv=True, venv_path='.venv')

# Quiet mode (only show errors)
auto_install(quiet=True)

# Generate requirements.txt with pinned versions
auto_install(generate_requirements=True)

# Custom requirements file path
auto_install(generate_requirements=True, requirements_path='deps.txt')
```

---

## 🎯 How It Works

1. **Parse Imports**: Uses Python's AST to find all `import` and `from ... import` statements
2. **Filter Standard Library**: Removes built-in Python modules (e.g., `os`, `sys`, `json`)
3. **Filter Local Modules**: Excludes your project's own modules
4. **Map Module Names**: Converts import names to PyPI package names using `module_mappings.json` (e.g., `cv2` β†’ `opencv-python`)
5. **Check Installation**: Queries what's already installed to avoid redundant work
6. **Install Packages**: Uses pip to install missing packages
7. **Verify**: Confirms all required packages are present

---

## πŸ“Š Comparison with Other Tools

| Feature | requirements_installer | pipreqs | pigar | pythonrunscript |
|---------|----------------------|---------|-------|-----------------|
| Auto-detect imports | βœ… | βœ… | βœ… | ❌ |
| Auto-install packages | βœ… | ❌ | ❌ | βœ… |
| Generate requirements.txt | βœ… | βœ… | βœ… | ❌ |
| Pinned versions in output | βœ… | βœ… | βœ… | ❌ |
| One-step install + generate | βœ… | ❌ | ❌ | ❌ |
| Call from inside code | βœ… | ❌ | ❌ | ⚠️ |
| Jupyter notebook support | βœ… | ⚠️ | βœ… | ❌ |
| Interactive version selection | βœ… | ❌ | ❌ | ❌ |
| Virtual environment support | βœ… | ❌ | ❌ | βœ… |
| No source file modification | βœ… | βœ… | βœ… | ❌ |
| One-command operation | βœ… | ❌ | ❌ | βœ… |
| Easy to extend mappings | βœ… | ❌ | ❌ | ❌ |

**Why requirements_installer?**
- **pipreqs/pigar**: Generate `requirements.txt` but don't install (requires 2 steps)
- **pythonrunscript**: Installs but requires metadata comments in your code
- **requirements_installer**: 
  - ✨ Call `auto_install()` directly in your code
  - πŸ““ Full Jupyter/Colab support
  - πŸš€ Self-installing scripts
  - πŸ’ͺ 150+ module-to-package mappings
  - πŸ”§ Easy to extend via JSON file
  - πŸ“ **One command to install AND generate requirements.txt**

---

## πŸ§ͺ Module-to-Package Mappings

The tool includes smart mappings for 150+ common cases where the import name differs from the PyPI package name. These mappings are stored in `module_mappings.json` for easy maintenance and contributions.

**Common examples:**
```python
cv2          β†’ opencv-python
PIL          β†’ Pillow
sklearn      β†’ scikit-learn
yaml         β†’ PyYAML
bs4          β†’ beautifulsoup4
pptx         β†’ python-pptx
docx         β†’ python-docx
MySQLdb      β†’ mysqlclient
psycopg2     β†’ psycopg2-binary
telegram     β†’ python-telegram-bot
discord      β†’ discord.py
serial       β†’ pyserial
git          β†’ GitPython
# ... and 140+ more!
```

### Adding Your Own Mappings

It's easy to contribute new mappings! Just edit `module_mappings.json`:

```json
{
  "your_import_name": "pypi-package-name",
  "another_module": "another-package"
}
```

Then submit a pull request or use your custom version locally.

---

## ⚠️ Limitations

- **One-hop scanning**: Only follows local imports one level deep (for speed)
- **Dynamic imports**: Limited detection of `importlib.import_module()` calls
- **Conditional imports**: Treats all imports equally (no context analysis)
- **Version conflicts**: Doesn't resolve complex dependency conflicts (delegates to pip)
- **Jupyter notebooks**: Best results when notebook is saved. If not found, falls back to scanning executed cells only

These are deliberate trade-offs for simplicity and speed. For complex projects with intricate dependency trees, consider using Poetry or Pipenv.

---

## πŸ†˜ Troubleshooting

### Imports not detected in Jupyter/Colab

**Problem:** Some imports are not being detected.

**Solution:** 

The tool automatically tries to find your notebook file to scan ALL cells. If it can't find the file:

1. **Save your notebook** - This helps the tool locate and read it
2. **For Colab**: Mount Google Drive if your notebook is stored there:
```python
from google.colab import drive
drive.mount('/content/drive')
```
3. **Fallback behavior**: If the notebook file isn't found, it scans executed cells only. In this case, run cells with imports before calling `auto_install()`.

### Command not found

```bash
# If 'requirements_installer' command not found, try:
python -m requirements_installer --file mycode.py

# Or check if installed:
pip show requirements_installer
```

---

## πŸ†š Command Line vs auto_install()

**Command Line** (traditional):
```bash
pip install requirements_installer
requirements_installer --file mycode.py
python mycode.py
```

**auto_install()** (modern - recommended):
```bash
python mycode.py  # That's it! Self-installing
```

---

## 🀝 Contributing

Contributions are welcome! Here are some ways you can help:

- πŸ› Report bugs and issues
- πŸ’‘ Suggest new features or improvements
- πŸ“ Improve documentation
- πŸ”§ Submit pull requests
- ⭐ Add more module-to-package mappings to `module_mappings.json`

### Development Setup

```bash
git clone https://github.com/FH-Prevail/requirements_installer.git
cd requirements_installer
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -e .
```

### Adding New Mappings

To add new module-to-package mappings:

1. Edit `module_mappings.json`
2. Add your mapping: `"import_name": "pypi-package-name"`
3. Test it works
4. Submit a pull request!

**Note:** Only add mappings where the import name differs from the package name. No need for entries like `"torch": "torch"`.

### Running Tests

```bash
python -m pytest tests/
```

---

## πŸ“„ License

MIT License - see [LICENSE](LICENSE) file for details.

---

## πŸ™ Acknowledgments

Inspired by:
- [pipreqs](https://github.com/bndr/pipreqs) - For the import scanning approach
- [pigar](https://github.com/damnever/pigar) - For AST parsing techniques
- [pythonrunscript](https://github.com/AnswerDotAI/pythonrunscript) - For auto-installation workflows

---

## πŸ“¬ Contact & Support

- **Issues**: [GitHub Issues](https://github.com/FH-Prevail/requirements_installer/issues)
- **Discussions**: [GitHub Discussions](https://github.com/FH-Prevail/requirements_installer/discussions)
- **Repository**: [github.com/FH-Prevail/requirements_installer](https://github.com/FH-Prevail/requirements_installer)
- **Author**: Sina Mirshahi

---

## πŸŽ“ Perfect For:

- πŸ““ **Jupyter/Colab notebooks** - Make them truly self-contained
- πŸš€ **Quick scripts** - No setup, just run
- πŸ‘₯ **Sharing code** - Recipients don't need to know about dependencies
- πŸŽ“ **Teaching** - Students can run examples immediately
- πŸ”¬ **Research** - Reproducible notebooks that "just work"
- πŸ€– **Automation** - Scripts that set themselves up
- πŸ“‹ **Team collaboration** - Generate requirements.txt for reproducible environments
- πŸ”„ **CI/CD pipelines** - Automatically detect and document dependencies

---

**Made with ❀️ by Sina Mirshahi**

**Star this repo if you find it useful!** ⭐ 

[Report Bug](https://github.com/FH-Prevail/requirements_installer/issues) Β· [Request Feature](https://github.com/FH-Prevail/requirements_installer/issues) Β· [Contribute](https://github.com/FH-Prevail/requirements_installer/pulls)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "requirements-installer",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "pip, requirements, dependencies, automation, installer",
    "author": null,
    "author_email": "Sina Mirshahi <sina7th@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/f3/c9/034d5a26079fca07299a4841c07aeaff5de64a7e136b23fa5a5550b35fb1/requirements_installer-1.1.0.tar.gz",
    "platform": null,
    "description": "# Requirements Installer \ud83d\ude80\r\n\r\n**Tired of hunting down missing Python dependencies?** Requirements Installer automatically detects and installs all third-party packages your Python script needs\u2014no `requirements.txt` needed!\r\n\r\nSimply point it at your Python file, and it handles the rest. Perfect for running unfamiliar scripts, quick prototyping, or setting up development environments.\r\n\r\n## \ud83c\udfaf Two Ways to Use\r\n\r\n### 1\ufe0f\u20e3 Inside Your Code (Easiest!)\r\n```python\r\nfrom requirements_installer import auto_install\r\nauto_install()\r\n```\r\n\r\n### 2\ufe0f\u20e3 Command Line\r\n```bash\r\nrequirements_installer --file mycode.py\r\n```\r\n\r\n---\r\n\r\n## \u2728 Features\r\n\r\n- **\u26a1 Auto-Install Inside Code** - Just `from requirements_installer import auto_install; auto_install()` and you're done!\r\n- **\ud83d\udcd3 Jupyter/Colab Support** - Scans and installs from `.ipynb` files automatically\r\n- **\ud83d\udd0d Smart Import Detection** - Automatically scans your Python files for all third-party imports\r\n- **\ud83d\udce6 One-Command Install** - Detects and installs dependencies in a single step\r\n- **\ud83d\udcdd Generate requirements.txt** - Automatically create requirements.txt with pinned versions\r\n- **\ud83c\udfaf Interactive Version Selection** - Optionally choose specific versions for each package\r\n- **\ud83d\udd12 Virtual Environment Support** - Create and install into isolated environments\r\n- **\ud83e\udde0 Intelligent Filtering** - Excludes stdlib and local modules automatically\r\n- **\ud83d\udcc4 Module-to-Package Mapping** - Handles 150+ tricky cases like `cv2` \u2192 `opencv-python`, `pptx` \u2192 `python-pptx`\r\n- **\ud83d\udd27 Easy to Extend** - Add new mappings by editing a simple JSON file\r\n- **\ud83c\udf0d One-Hop Local Import Scanning** - Follows local imports to catch all dependencies\r\n- **\ud83d\udcaa Pure Python** - No external dependencies required\r\n\r\n---\r\n\r\n## \ud83d\udd25 Installation\r\n\r\n```bash\r\npip install requirements_installer\r\n```\r\n\r\nOr install from source:\r\n\r\n```bash\r\ngit clone https://github.com/FH-Prevail/requirements_installer.git\r\ncd requirements_installer\r\npip install -e .\r\n```\r\n\r\n---\r\n\r\n## \ud83d\ude80 Quick Start\r\n\r\n### \u2b50 NEW: Auto-Install Inside Your Code (Recommended!)\r\n\r\n**The easiest way - just add 2 lines to your script:**\r\n\r\n```python\r\nfrom requirements_installer import auto_install\r\nauto_install()\r\n\r\n# Now use any packages - they'll be auto-installed if missing!\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n```\r\n\r\n**Perfect for Jupyter/Colab notebooks:**\r\n\r\n```python\r\n# Cell 1: Your imports and code\r\nimport pandas as pd\r\nimport torch\r\nfrom transformers import AutoModel\r\n# ... your code ...\r\n\r\n# Cell 2: Install everything (run this if imports fail)\r\n!pip install -q requirements_installer\r\nfrom requirements_installer import auto_install\r\nauto_install()  # Scans all cells above and installs missing packages!\r\n\r\n# Now re-run Cell 1 and it will work!\r\n```\r\n\r\n**Or install dependencies first:**\r\n\r\n```python\r\n# Cell 1: Setup (run first)\r\n!pip install -q requirements_installer\r\nfrom requirements_installer import auto_install\r\nauto_install()  # If you have imports in other cells, it will find them\r\n\r\n# Cell 2+: Your code with any imports\r\nimport torch\r\nimport transformers\r\n```\r\n\r\n### Basic Command-Line Usage\r\n\r\n**After `pip install requirements_installer`, use it as a command:**\r\n\r\n```bash\r\n# Scan and install dependencies for a Python file\r\nrequirements_installer --file mycode.py\r\n\r\n# Works with Jupyter notebooks too!\r\nrequirements_installer --file notebook.ipynb\r\n```\r\n\r\n### With Virtual Environment\r\n\r\n```bash\r\n# Create a venv and install dependencies there\r\nrequirements_installer --file mycode.py --use-venv --venv-path .venv\r\n```\r\n\r\n### Interactive Version Selection\r\n\r\n```bash\r\n# Choose specific versions for each package\r\nrequirements_installer --file mycode.py --ask-version\r\n```\r\n\r\nExample interaction:\r\n```\r\n==================================================\r\nVersion Selection\r\n==================================================\r\n\r\nInstall latest version of 'numpy'? [Y/n]: n\r\nEnter version for 'numpy' (e.g., 1.2.3): 1.24.0\r\n\r\nInstall latest version of 'pandas'? [Y/n]: y\r\n\r\nInstall latest version of 'requests'? [Y/n]: \r\n```\r\n\r\n### Print Requirements Only\r\n\r\n```bash\r\n# Just show what would be installed, don't install\r\nrequirements_installer --file mycode.py --print-requirements\r\n```\r\n\r\n### Generate requirements.txt\r\n\r\n```bash\r\n# Install dependencies AND generate requirements.txt with pinned versions\r\nrequirements_installer --file mycode.py --generate-requirements\r\n```\r\n\r\nThis creates a `requirements.txt` file like:\r\n```\r\n# Generated by requirements_installer\r\n# Install with: pip install -r requirements.txt\r\n\r\nbeautifulsoup4==4.12.2\r\nnumpy==1.24.3\r\npandas==2.0.2\r\nrequests==2.31.0\r\n```\r\n\r\nYou can specify a custom output path:\r\n```bash\r\nrequirements_installer --file mycode.py --generate-requirements --requirements-path deps.txt\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udcd6 Usage Examples\r\n\r\n### Example 1: Auto-Install in Script (NEW! \ud83c\udf89)\r\nMake your scripts self-installing:\r\n\r\n```python\r\n# my_analysis.py\r\nfrom requirements_installer import auto_install\r\nauto_install()\r\n\r\n# Now use any packages!\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndf = pd.read_csv('data.csv')\r\nplt.plot(df['x'], df['y'])\r\nplt.show()\r\n```\r\n\r\n**Just run it:**\r\n```bash\r\npython my_analysis.py  # Auto-installs pandas, numpy, matplotlib!\r\n```\r\n\r\n### Example 2: Jupyter/Colab Notebook\r\n\r\n**Option A - Install before running (recommended):**\r\n```python\r\n# Cell 1: One-time setup\r\n!pip install -q requirements_installer\r\nfrom requirements_installer import auto_install\r\nauto_install()  # Scans ALL cells in notebook (even unexecuted ones!)\r\n\r\n# Cell 2+: Now run your code\r\nimport pandas as pd\r\nimport torch\r\nfrom transformers import AutoModel\r\nmodel = AutoModel.from_pretrained('bert-base-uncased')\r\n```\r\n\r\n**Option B - Fix import errors after they happen:**\r\n```python\r\n# Cell 1: Try to run your code\r\nimport pandas as pd\r\nimport torch\r\n# ImportError: No module named 'torch'\r\n\r\n# Cell 2: Install missing dependencies\r\n!pip install -q requirements_installer\r\nfrom requirements_installer import auto_install\r\nauto_install()  # Scans ALL cells and installs what's needed!\r\n\r\n# Cell 3: Re-run Cell 1 - now it works!\r\n```\r\n\r\n**How it works in Colab/Jupyter:**\r\n- Automatically finds and reads your notebook file\r\n- Scans **ALL cells** (even unexecuted ones!)\r\n- Installs missing packages automatically\r\n- No need to execute cells first - just call `auto_install()`\r\n\r\n### Example 3: Quick Script Setup\r\nYou clone a repo without a `requirements.txt`:\r\n\r\n```bash\r\nrequirements_installer --file app.py\r\n```\r\n\r\nOutput:\r\n```\r\nDetected environment: current Python at /usr/bin/python3\r\nEntry file: /home/user/project/app.py\r\nInstalling: numpy pandas requests\r\n\r\n==================================================\r\nInstallation Summary\r\n==================================================\r\nInstalled: numpy, pandas, requests\r\nAlready satisfied: (none)\r\nAll requested packages are now present.\r\n```\r\n\r\n### Example 4: Isolated Development Environment\r\n\r\n```bash\r\nrequirements_installer --file main.py --use-venv\r\n```\r\n\r\nCreates a `.venv` folder and installs all dependencies there, keeping your system Python clean.\r\n\r\n### Example 5: Precise Version Control\r\n\r\n```bash\r\nrequirements_installer --file analysis.py --ask-version\r\n```\r\n\r\nPrompts you for each package, letting you pin versions for reproducibility.\r\n\r\n### Example 6: Generate requirements.txt for Team Sharing\r\n\r\nYou inherit a script without documentation:\r\n\r\n```bash\r\nrequirements_installer --file data_pipeline.py --generate-requirements\r\n```\r\n\r\nOutput:\r\n```\r\nDetected environment: current Python at /usr/bin/python3\r\nEntry file: /home/user/project/data_pipeline.py\r\nInstalling: pandas numpy sqlalchemy psycopg2-binary\r\n\r\n==================================================\r\nInstallation Summary\r\n==================================================\r\nInstalled: pandas, numpy, sqlalchemy, psycopg2-binary\r\nAlready satisfied: (none)\r\nAll requested packages are now present.\r\n\r\n\ud83d\udcdd Generating requirements.txt...\r\n\u2705 Generated requirements.txt with 4 packages\r\n\r\nYou can now install these dependencies with:\r\n  pip install -r requirements.txt\r\n```\r\n\r\nThe generated `requirements.txt`:\r\n```\r\n# Generated by requirements_installer\r\n# Install with: pip install -r requirements.txt\r\n\r\nnumpy==1.24.3\r\npandas==2.0.2\r\npsycopg2-binary==2.9.6\r\nsqlalchemy==2.0.15\r\n```\r\n\r\nNow you can share this with your team for reproducible installations!\r\n\r\n---\r\n\r\n## \ud83d\udd27 Command-Line Options\r\n\r\n**After installation, use the `requirements_installer` command:**\r\n\r\n```\r\nusage: requirements_installer [-h] --file FILE [--use-venv] \r\n                              [--venv-path VENV_PATH]\r\n                              [--print-requirements] [--ask-version]\r\n                              [--generate-requirements]\r\n                              [--requirements-path REQUIREMENTS_PATH]\r\n\r\noptions:\r\n  -h, --help            Show this help message and exit\r\n  --file FILE           Entry Python file or Jupyter notebook (.ipynb) to scan\r\n  --use-venv            Create and use a virtual environment\r\n  --venv-path VENV_PATH \r\n                        Where to create the venv (default: .venv)\r\n  --print-requirements  Only print inferred packages and exit\r\n  --ask-version         Interactively ask for version preference for each package\r\n  --generate-requirements\r\n                        Generate requirements.txt with pinned versions after installation\r\n  --requirements-path REQUIREMENTS_PATH\r\n                        Path for requirements.txt file (default: requirements.txt)\r\n```\r\n\r\n**Examples:**\r\n```bash\r\n# Basic usage\r\nrequirements_installer --file mycode.py\r\n\r\n# With virtual environment\r\nrequirements_installer --file mycode.py --use-venv\r\n\r\n# Interactive version selection\r\nrequirements_installer --file mycode.py --ask-version\r\n\r\n# Scan Jupyter notebook\r\nrequirements_installer --file notebook.ipynb\r\n\r\n# Generate requirements.txt\r\nrequirements_installer --file mycode.py --generate-requirements\r\n\r\n# Custom requirements file path\r\nrequirements_installer --file mycode.py --generate-requirements --requirements-path deps.txt\r\n```\r\n\r\n**Note:** If you cloned the repository and want to run directly without installation:\r\n```bash\r\npython requirements_installer.py --file mycode.py\r\n```\r\n\r\n## \ud83d\udc0d Python API\r\n\r\n```python\r\nfrom requirements_installer import auto_install\r\n\r\n# Auto-detect and install (recommended)\r\nauto_install()\r\n\r\n# Specify file explicitly\r\nauto_install(file_path='script.py')\r\nauto_install(file_path='notebook.ipynb')\r\n\r\n# Use virtual environment\r\nauto_install(use_venv=True, venv_path='.venv')\r\n\r\n# Quiet mode (only show errors)\r\nauto_install(quiet=True)\r\n\r\n# Generate requirements.txt with pinned versions\r\nauto_install(generate_requirements=True)\r\n\r\n# Custom requirements file path\r\nauto_install(generate_requirements=True, requirements_path='deps.txt')\r\n```\r\n\r\n---\r\n\r\n## \ud83c\udfaf How It Works\r\n\r\n1. **Parse Imports**: Uses Python's AST to find all `import` and `from ... import` statements\r\n2. **Filter Standard Library**: Removes built-in Python modules (e.g., `os`, `sys`, `json`)\r\n3. **Filter Local Modules**: Excludes your project's own modules\r\n4. **Map Module Names**: Converts import names to PyPI package names using `module_mappings.json` (e.g., `cv2` \u2192 `opencv-python`)\r\n5. **Check Installation**: Queries what's already installed to avoid redundant work\r\n6. **Install Packages**: Uses pip to install missing packages\r\n7. **Verify**: Confirms all required packages are present\r\n\r\n---\r\n\r\n## \ud83d\udcca Comparison with Other Tools\r\n\r\n| Feature | requirements_installer | pipreqs | pigar | pythonrunscript |\r\n|---------|----------------------|---------|-------|-----------------|\r\n| Auto-detect imports | \u2705 | \u2705 | \u2705 | \u274c |\r\n| Auto-install packages | \u2705 | \u274c | \u274c | \u2705 |\r\n| Generate requirements.txt | \u2705 | \u2705 | \u2705 | \u274c |\r\n| Pinned versions in output | \u2705 | \u2705 | \u2705 | \u274c |\r\n| One-step install + generate | \u2705 | \u274c | \u274c | \u274c |\r\n| Call from inside code | \u2705 | \u274c | \u274c | \u26a0\ufe0f |\r\n| Jupyter notebook support | \u2705 | \u26a0\ufe0f | \u2705 | \u274c |\r\n| Interactive version selection | \u2705 | \u274c | \u274c | \u274c |\r\n| Virtual environment support | \u2705 | \u274c | \u274c | \u2705 |\r\n| No source file modification | \u2705 | \u2705 | \u2705 | \u274c |\r\n| One-command operation | \u2705 | \u274c | \u274c | \u2705 |\r\n| Easy to extend mappings | \u2705 | \u274c | \u274c | \u274c |\r\n\r\n**Why requirements_installer?**\r\n- **pipreqs/pigar**: Generate `requirements.txt` but don't install (requires 2 steps)\r\n- **pythonrunscript**: Installs but requires metadata comments in your code\r\n- **requirements_installer**: \r\n  - \u2728 Call `auto_install()` directly in your code\r\n  - \ud83d\udcd3 Full Jupyter/Colab support\r\n  - \ud83d\ude80 Self-installing scripts\r\n  - \ud83d\udcaa 150+ module-to-package mappings\r\n  - \ud83d\udd27 Easy to extend via JSON file\r\n  - \ud83d\udcdd **One command to install AND generate requirements.txt**\r\n\r\n---\r\n\r\n## \ud83e\uddea Module-to-Package Mappings\r\n\r\nThe tool includes smart mappings for 150+ common cases where the import name differs from the PyPI package name. These mappings are stored in `module_mappings.json` for easy maintenance and contributions.\r\n\r\n**Common examples:**\r\n```python\r\ncv2          \u2192 opencv-python\r\nPIL          \u2192 Pillow\r\nsklearn      \u2192 scikit-learn\r\nyaml         \u2192 PyYAML\r\nbs4          \u2192 beautifulsoup4\r\npptx         \u2192 python-pptx\r\ndocx         \u2192 python-docx\r\nMySQLdb      \u2192 mysqlclient\r\npsycopg2     \u2192 psycopg2-binary\r\ntelegram     \u2192 python-telegram-bot\r\ndiscord      \u2192 discord.py\r\nserial       \u2192 pyserial\r\ngit          \u2192 GitPython\r\n# ... and 140+ more!\r\n```\r\n\r\n### Adding Your Own Mappings\r\n\r\nIt's easy to contribute new mappings! Just edit `module_mappings.json`:\r\n\r\n```json\r\n{\r\n  \"your_import_name\": \"pypi-package-name\",\r\n  \"another_module\": \"another-package\"\r\n}\r\n```\r\n\r\nThen submit a pull request or use your custom version locally.\r\n\r\n---\r\n\r\n## \u26a0\ufe0f Limitations\r\n\r\n- **One-hop scanning**: Only follows local imports one level deep (for speed)\r\n- **Dynamic imports**: Limited detection of `importlib.import_module()` calls\r\n- **Conditional imports**: Treats all imports equally (no context analysis)\r\n- **Version conflicts**: Doesn't resolve complex dependency conflicts (delegates to pip)\r\n- **Jupyter notebooks**: Best results when notebook is saved. If not found, falls back to scanning executed cells only\r\n\r\nThese are deliberate trade-offs for simplicity and speed. For complex projects with intricate dependency trees, consider using Poetry or Pipenv.\r\n\r\n---\r\n\r\n## \ud83c\udd98 Troubleshooting\r\n\r\n### Imports not detected in Jupyter/Colab\r\n\r\n**Problem:** Some imports are not being detected.\r\n\r\n**Solution:** \r\n\r\nThe tool automatically tries to find your notebook file to scan ALL cells. If it can't find the file:\r\n\r\n1. **Save your notebook** - This helps the tool locate and read it\r\n2. **For Colab**: Mount Google Drive if your notebook is stored there:\r\n```python\r\nfrom google.colab import drive\r\ndrive.mount('/content/drive')\r\n```\r\n3. **Fallback behavior**: If the notebook file isn't found, it scans executed cells only. In this case, run cells with imports before calling `auto_install()`.\r\n\r\n### Command not found\r\n\r\n```bash\r\n# If 'requirements_installer' command not found, try:\r\npython -m requirements_installer --file mycode.py\r\n\r\n# Or check if installed:\r\npip show requirements_installer\r\n```\r\n\r\n---\r\n\r\n## \ud83c\udd9a Command Line vs auto_install()\r\n\r\n**Command Line** (traditional):\r\n```bash\r\npip install requirements_installer\r\nrequirements_installer --file mycode.py\r\npython mycode.py\r\n```\r\n\r\n**auto_install()** (modern - recommended):\r\n```bash\r\npython mycode.py  # That's it! Self-installing\r\n```\r\n\r\n---\r\n\r\n## \ud83e\udd1d Contributing\r\n\r\nContributions are welcome! Here are some ways you can help:\r\n\r\n- \ud83d\udc1b Report bugs and issues\r\n- \ud83d\udca1 Suggest new features or improvements\r\n- \ud83d\udcdd Improve documentation\r\n- \ud83d\udd27 Submit pull requests\r\n- \u2b50 Add more module-to-package mappings to `module_mappings.json`\r\n\r\n### Development Setup\r\n\r\n```bash\r\ngit clone https://github.com/FH-Prevail/requirements_installer.git\r\ncd requirements_installer\r\npython -m venv venv\r\nsource venv/bin/activate  # On Windows: venv\\Scripts\\activate\r\npip install -e .\r\n```\r\n\r\n### Adding New Mappings\r\n\r\nTo add new module-to-package mappings:\r\n\r\n1. Edit `module_mappings.json`\r\n2. Add your mapping: `\"import_name\": \"pypi-package-name\"`\r\n3. Test it works\r\n4. Submit a pull request!\r\n\r\n**Note:** Only add mappings where the import name differs from the package name. No need for entries like `\"torch\": \"torch\"`.\r\n\r\n### Running Tests\r\n\r\n```bash\r\npython -m pytest tests/\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udcc4 License\r\n\r\nMIT License - see [LICENSE](LICENSE) file for details.\r\n\r\n---\r\n\r\n## \ud83d\ude4f Acknowledgments\r\n\r\nInspired by:\r\n- [pipreqs](https://github.com/bndr/pipreqs) - For the import scanning approach\r\n- [pigar](https://github.com/damnever/pigar) - For AST parsing techniques\r\n- [pythonrunscript](https://github.com/AnswerDotAI/pythonrunscript) - For auto-installation workflows\r\n\r\n---\r\n\r\n## \ud83d\udcec Contact & Support\r\n\r\n- **Issues**: [GitHub Issues](https://github.com/FH-Prevail/requirements_installer/issues)\r\n- **Discussions**: [GitHub Discussions](https://github.com/FH-Prevail/requirements_installer/discussions)\r\n- **Repository**: [github.com/FH-Prevail/requirements_installer](https://github.com/FH-Prevail/requirements_installer)\r\n- **Author**: Sina Mirshahi\r\n\r\n---\r\n\r\n## \ud83c\udf93 Perfect For:\r\n\r\n- \ud83d\udcd3 **Jupyter/Colab notebooks** - Make them truly self-contained\r\n- \ud83d\ude80 **Quick scripts** - No setup, just run\r\n- \ud83d\udc65 **Sharing code** - Recipients don't need to know about dependencies\r\n- \ud83c\udf93 **Teaching** - Students can run examples immediately\r\n- \ud83d\udd2c **Research** - Reproducible notebooks that \"just work\"\r\n- \ud83e\udd16 **Automation** - Scripts that set themselves up\r\n- \ud83d\udccb **Team collaboration** - Generate requirements.txt for reproducible environments\r\n- \ud83d\udd04 **CI/CD pipelines** - Automatically detect and document dependencies\r\n\r\n---\r\n\r\n**Made with \u2764\ufe0f by Sina Mirshahi**\r\n\r\n**Star this repo if you find it useful!** \u2b50 \r\n\r\n[Report Bug](https://github.com/FH-Prevail/requirements_installer/issues) \u00b7 [Request Feature](https://github.com/FH-Prevail/requirements_installer/issues) \u00b7 [Contribute](https://github.com/FH-Prevail/requirements_installer/pulls)\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Automatically detect and install Python dependencies from your code",
    "version": "1.1.0",
    "project_urls": {
        "Homepage": "https://github.com/FH-Prevail/requirements_installer",
        "Issues": "https://github.com/FH-Prevail/requirements_installer/issues",
        "Repository": "https://github.com/FH-Prevail/requirements_installer"
    },
    "split_keywords": [
        "pip",
        " requirements",
        " dependencies",
        " automation",
        " installer"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "fbe710367603a532d495345ad7a34f1379ae5be629152c72d26b3b3f3cb28d3f",
                "md5": "ded2ff4bf448066d996ccb159d3a7bd0",
                "sha256": "78ea8f4bd7cae283537cd95da2c14efe1039d6aa9edbd7d1c997e2a25e095293"
            },
            "downloads": -1,
            "filename": "requirements_installer-1.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ded2ff4bf448066d996ccb159d3a7bd0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 17703,
            "upload_time": "2025-10-10T06:34:43",
            "upload_time_iso_8601": "2025-10-10T06:34:43.853774Z",
            "url": "https://files.pythonhosted.org/packages/fb/e7/10367603a532d495345ad7a34f1379ae5be629152c72d26b3b3f3cb28d3f/requirements_installer-1.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f3c9034d5a26079fca07299a4841c07aeaff5de64a7e136b23fa5a5550b35fb1",
                "md5": "b8e0f75b72f6c6278f9ac23c84122485",
                "sha256": "39680f42a30fa643e9e04efe577508bad03bbd01f4bbd93f9c98619e93552a33"
            },
            "downloads": -1,
            "filename": "requirements_installer-1.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "b8e0f75b72f6c6278f9ac23c84122485",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 17815,
            "upload_time": "2025-10-10T06:34:47",
            "upload_time_iso_8601": "2025-10-10T06:34:47.736917Z",
            "url": "https://files.pythonhosted.org/packages/f3/c9/034d5a26079fca07299a4841c07aeaff5de64a7e136b23fa5a5550b35fb1/requirements_installer-1.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-10 06:34:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "FH-Prevail",
    "github_project": "requirements_installer",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "requirements-installer"
}
        
Elapsed time: 2.17043s