Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse files- DEPLOYMENT_CHECKLIST.md +79 -0
- GITHUB_SETUP.md +43 -0
- PROJECT_WORKFLOW_REPORT.md +72 -0
- README.md +27 -6
- app.py +72 -0
- level_1_text_summarization.py +78 -0
- requirements.txt +4 -0
- security_check.py +83 -0
- tests/test_text_summarization.py +52 -0
- upload_to_hub.py +54 -0
DEPLOYMENT_CHECKLIST.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚀 Deployment Checklist
|
| 2 |
+
|
| 3 |
+
## Pre-Deployment Security & Quality Checks
|
| 4 |
+
|
| 5 |
+
- [x] **Git Initialization**
|
| 6 |
+
- [x] Repository initialized with proper commit history
|
| 7 |
+
- [x] Comprehensive `.gitignore` excludes sensitive files, cache, and build artifacts
|
| 8 |
+
- [x] All project files properly staged and committed
|
| 9 |
+
|
| 10 |
+
- [x] **Security Verification**
|
| 11 |
+
- [x] No hardcoded API keys, tokens, or credentials in code
|
| 12 |
+
- [x] Security scan completed - no sensitive data patterns detected
|
| 13 |
+
- [x] Upload script uses secure authentication via HF CLI
|
| 14 |
+
- [x] Personal data and local configurations excluded from version control
|
| 15 |
+
|
| 16 |
+
- [x] **Code Quality**
|
| 17 |
+
- [x] All dependencies specified with version constraints
|
| 18 |
+
- [x] Unit tests pass and provide good coverage
|
| 19 |
+
- [x] Code is modular and well-documented
|
| 20 |
+
- [x] Error handling implemented for edge cases
|
| 21 |
+
|
| 22 |
+
- [x] **Documentation**
|
| 23 |
+
- [x] README.md formatted for Hugging Face Spaces with proper YAML frontmatter
|
| 24 |
+
- [x] Clear usage instructions and model information provided
|
| 25 |
+
- [x] Technical details and dependencies documented
|
| 26 |
+
- [x] Setup instructions for both GitHub and Hugging Face included
|
| 27 |
+
|
| 28 |
+
## Deployment Steps
|
| 29 |
+
|
| 30 |
+
### 1. GitHub Repository Setup
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
# After creating repository on GitHub:
|
| 34 |
+
git remote add origin https://github.com/YOUR_USERNAME/text-summarization-huggingface.git
|
| 35 |
+
git push -u origin master
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
### 2. Hugging Face Spaces Deployment
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
# Authenticate (one-time setup)
|
| 42 |
+
huggingface-cli login
|
| 43 |
+
|
| 44 |
+
# Deploy to Spaces
|
| 45 |
+
python3 upload_to_hub.py
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
### 3. Post-Deployment Verification
|
| 49 |
+
|
| 50 |
+
- [ ] **GitHub Repository**
|
| 51 |
+
- [ ] Code visible and properly formatted
|
| 52 |
+
- [ ] README displays correctly
|
| 53 |
+
- [ ] No sensitive files in history
|
| 54 |
+
|
| 55 |
+
- [ ] **Hugging Face Spaces**
|
| 56 |
+
- [ ] Space builds successfully
|
| 57 |
+
- [ ] Gradio interface loads and functions correctly
|
| 58 |
+
- [ ] Model downloads and initializes properly
|
| 59 |
+
- [ ] Demo works with sample text input
|
| 60 |
+
|
| 61 |
+
## Environment Requirements
|
| 62 |
+
|
| 63 |
+
- Python 3.8+
|
| 64 |
+
- transformers >= 4.21.0
|
| 65 |
+
- torch >= 1.12.0
|
| 66 |
+
- gradio >= 3.35.0
|
| 67 |
+
- huggingface_hub >= 0.16.0
|
| 68 |
+
|
| 69 |
+
## Portfolio Integration
|
| 70 |
+
|
| 71 |
+
This project demonstrates:
|
| 72 |
+
- ✅ **NLP Expertise**: Text summarization using state-of-the-art models
|
| 73 |
+
- ✅ **Full-Stack Skills**: Interactive web interface with Gradio
|
| 74 |
+
- ✅ **DevOps Practices**: Proper testing, documentation, and deployment
|
| 75 |
+
- ✅ **Open Source Contribution**: Professional-grade code ready for public repositories
|
| 76 |
+
|
| 77 |
+
---
|
| 78 |
+
|
| 79 |
+
**Ready for deployment!** 🎉
|
GITHUB_SETUP.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GitHub Repository Setup
|
| 2 |
+
|
| 3 |
+
## To push this project to GitHub:
|
| 4 |
+
|
| 5 |
+
1. **Create a new repository on GitHub**
|
| 6 |
+
- Go to https://github.com/new
|
| 7 |
+
- Repository name: `text-summarization-huggingface`
|
| 8 |
+
- Description: "Text Summarization with Transformers - Interactive Gradio demo using DistilBART for portfolio showcase"
|
| 9 |
+
- Choose Public (for portfolio visibility)
|
| 10 |
+
- Don't initialize with README (we already have one)
|
| 11 |
+
|
| 12 |
+
2. **Connect your local repository to GitHub**
|
| 13 |
+
```bash
|
| 14 |
+
# Add your GitHub repository as remote origin
|
| 15 |
+
git remote add origin https://github.com/YOUR_USERNAME/text-summarization-huggingface.git
|
| 16 |
+
|
| 17 |
+
# Push your code to GitHub
|
| 18 |
+
git push -u origin master
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
3. **Alternative: Using SSH (if configured)**
|
| 22 |
+
```bash
|
| 23 |
+
git remote add origin git@github.com:YOUR_USERNAME/text-summarization-huggingface.git
|
| 24 |
+
git push -u origin master
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
## For Hugging Face Spaces:
|
| 28 |
+
|
| 29 |
+
1. **Authenticate with Hugging Face**
|
| 30 |
+
```bash
|
| 31 |
+
huggingface-cli login
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
2. **Upload to Hugging Face Spaces**
|
| 35 |
+
```bash
|
| 36 |
+
python3 upload_to_hub.py
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
## Security Notes:
|
| 40 |
+
- ✅ `.gitignore` excludes all sensitive files and cache directories
|
| 41 |
+
- ✅ No hardcoded tokens or credentials in any files
|
| 42 |
+
- ✅ Upload script uses secure authentication via HF CLI
|
| 43 |
+
- ✅ Model files and cache are excluded from version control
|
PROJECT_WORKFLOW_REPORT.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project Workflow Report: From Development to Deployment
|
| 2 |
+
|
| 3 |
+
This document outlines the standard procedures and workarounds used to successfully develop, test, and deploy a machine learning project to the Hugging Face Hub. This workflow can be adapted for future AI portfolio projects.
|
| 4 |
+
|
| 5 |
+
## 1. Project Scaffolding and Development
|
| 6 |
+
|
| 7 |
+
The initial phase focuses on setting up a clean project structure and developing the core application logic.
|
| 8 |
+
|
| 9 |
+
### Key Steps:
|
| 10 |
+
|
| 11 |
+
1. **Initial Script (`level_1_sentiment_analysis.py`):**
|
| 12 |
+
* Began with a basic Python script to perform sentiment analysis using the Hugging Face `transformers` library.
|
| 13 |
+
* Leveraged the high-level `pipeline` API to load a pre-trained model (`finiteautomata/bertweet-base-sentiment-analysis`).
|
| 14 |
+
* Included a check for GPU availability (`torch.cuda.is_available()`) to ensure hardware acceleration is used when possible.
|
| 15 |
+
|
| 16 |
+
2. **Dependency Management (`requirements.txt`):**
|
| 17 |
+
* Created a `requirements.txt` file early in the process.
|
| 18 |
+
* All Python dependencies (`transformers`, `torch`, `emoji`, `gradio`) were added to this file to ensure the environment is reproducible.
|
| 19 |
+
* **Procedure:** Use `pip install -r requirements.txt` to set up a new environment.
|
| 20 |
+
|
| 21 |
+
3. **Handling System Python Environments:**
|
| 22 |
+
* **Issue:** The system's Python environment was externally managed, preventing direct installation of packages with `pip`.
|
| 23 |
+
* **Workaround:** Used the `--break-system-packages` flag (e.g., `pip3 install emoji --break-system-packages`). This should be used with caution, but is effective for containerized or controlled development environments.
|
| 24 |
+
|
| 25 |
+
## 2. Testing and Validation
|
| 26 |
+
|
| 27 |
+
A robust testing phase ensures the code is reliable and maintainable.
|
| 28 |
+
|
| 29 |
+
### Key Steps:
|
| 30 |
+
|
| 31 |
+
1. **Refactoring for Testability:**
|
| 32 |
+
* The initial script was refactored to separate concerns. The core logic (pipeline creation, analysis) was moved into dedicated functions (`get_pipeline`, `analyze_sentiments`) that could be tested independently of the main execution block and its console output.
|
| 33 |
+
|
| 34 |
+
2. **Creating a Test Suite (`tests/test_sentiment_analysis.py`):**
|
| 35 |
+
* Used Python's built-in `unittest` framework.
|
| 36 |
+
* Created a `tests/` directory to house all test files.
|
| 37 |
+
* **Test Cases:**
|
| 38 |
+
* A test to confirm the `get_pipeline` function returns a valid pipeline object.
|
| 39 |
+
* A test to validate the structure and format of the output from the `analyze_sentiments` function.
|
| 40 |
+
* A basic integration test to ensure the main `run_sentiment_analysis` function executes without errors.
|
| 41 |
+
|
| 42 |
+
3. **Running Tests:**
|
| 43 |
+
* **Procedure:** Tests were executed from the project root directory using the command: `python3 -m unittest discover tests`.
|
| 44 |
+
|
| 45 |
+
## 3. Deployment to Hugging Face Hub
|
| 46 |
+
|
| 47 |
+
This phase focuses on making the project accessible and interactive for a portfolio showcase.
|
| 48 |
+
|
| 49 |
+
### Key Steps:
|
| 50 |
+
|
| 51 |
+
1. **Creating an Interactive Demo (`app.py`):**
|
| 52 |
+
* Developed a simple web application using **Gradio**.
|
| 53 |
+
* The `app.py` script imports the necessary functions, loads the pipeline, and defines a user-friendly interface for real-time sentiment analysis.
|
| 54 |
+
|
| 55 |
+
2. **Authoring a Model Card (`README.md`):**
|
| 56 |
+
* The project's `README.md` was overwritten with a format optimized for the Hugging Face Hub.
|
| 57 |
+
* **YAML Front Matter:** Included a YAML block at the top to configure the Space (e.g., `title`, `emoji`, `sdk`, `app_file`).
|
| 58 |
+
* **Content:** The card explains the project's purpose, how to use the demo, and details about the underlying model.
|
| 59 |
+
|
| 60 |
+
3. **Publishing to the Hub (Troubleshooting & Solution):**
|
| 61 |
+
* **Attempt 1: `git push` with HTTPS:** Failed due to Hugging Face deprecating password authentication.
|
| 62 |
+
* **Attempt 2: `git push` with SSH:** An SSH key was successfully generated and added to the user's Hugging Face account. However, the push failed again due to the network blocking SSH traffic on port 22.
|
| 63 |
+
* **Successful Method: `huggingface_hub` Python Library:**
|
| 64 |
+
* A dedicated script (`upload_to_hub.py`) was created to programmatically upload the files.
|
| 65 |
+
* This script uses the `HfApi` class, which interacts with the Hub over standard HTTPS (port 443), bypassing network restrictions.
|
| 66 |
+
* **Procedure:**
|
| 67 |
+
1. Ensure you are logged in via the terminal: `huggingface-cli login`.
|
| 68 |
+
2. Run the upload script: `python3 upload_to_hub.py`.
|
| 69 |
+
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
This comprehensive workflow ensures that projects are not only well-developed and tested but also successfully deployed and presented in a professional manner, even when faced with common environmental and network-related challenges.
|
README.md
CHANGED
|
@@ -1,12 +1,33 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Text Summarization
|
| 3 |
+
emoji: 📝
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 3.35.2
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# 📝 Text Summarization with Transformers
|
| 13 |
+
|
| 14 |
+
This Hugging Face Space demonstrates how to perform text summarization using a pre-trained model from the `transformers` library. It provides a simple interface to generate a concise summary from a longer text document.
|
| 15 |
+
|
| 16 |
+
This project is part of a portfolio showcasing foundational AI/ML skills. It highlights the ability to leverage powerful, pre-trained models for common Natural Language Processing (NLP) tasks.
|
| 17 |
+
|
| 18 |
+
## 🚀 How to Use the Demo
|
| 19 |
+
|
| 20 |
+
1. **Enter Text:** Paste the long-form text you want to summarize into the "Original Text" input box.
|
| 21 |
+
2. **Generate Summary:** Click the **"Summarize"** button.
|
| 22 |
+
3. **View Result:** The generated summary will appear in the "Summarized Text" box on the right.
|
| 23 |
+
|
| 24 |
+
## 🧠 Model Information
|
| 25 |
+
|
| 26 |
+
This demo uses the [`sshleifer/distilbart-cnn-12-6`](https://huggingface.co/sshleifer/distilbart-cnn-12-6) model, a sequence-to-sequence model fine-tuned on the CNN/DailyMail dataset for summarization. It is a distilled version of the BART model, making it faster and more efficient while retaining high performance.
|
| 27 |
+
|
| 28 |
+
## 🛠️ Technical Details
|
| 29 |
+
|
| 30 |
+
- **Framework:** The interactive demo is built with [Gradio](https://www.gradio.app/).
|
| 31 |
+
- **Library:** The core summarization logic is powered by the Hugging Face [`transformers`](https://huggingface.co/docs/transformers/index) library.
|
| 32 |
+
- **Hardware:** The application is configured to leverage a GPU if one is available, which significantly speeds up the summarization process.
|
| 33 |
+
- **Workflow:** The project follows a standard development workflow, including dependency management (`requirements.txt`), refactoring for testability, and unit testing (`unittest`).
|
app.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from level_1_text_summarization import get_pipeline, summarize_text
|
| 3 |
+
|
| 4 |
+
# --- 1. Load the model and pipeline at startup ---
|
| 5 |
+
# This ensures the model is loaded only once, not on every prediction.
|
| 6 |
+
print("Initializing the summarization pipeline for the Gradio app...")
|
| 7 |
+
summarizer_pipeline = get_pipeline()
|
| 8 |
+
print("Pipeline ready for the app.")
|
| 9 |
+
|
| 10 |
+
# --- 2. Define the prediction function ---
|
| 11 |
+
# This function will be called when the user interacts with the Gradio interface.
|
| 12 |
+
def generate_summary(input_text):
|
| 13 |
+
"""
|
| 14 |
+
Takes raw text input and returns the summarized version.
|
| 15 |
+
"""
|
| 16 |
+
if not summarizer_pipeline:
|
| 17 |
+
return "Error: The summarization pipeline is not available."
|
| 18 |
+
|
| 19 |
+
# Use the existing function to generate the summary
|
| 20 |
+
summary = summarize_text(
|
| 21 |
+
summarizer=summarizer_pipeline,
|
| 22 |
+
text=input_text,
|
| 23 |
+
max_length=150, # Allow for longer summaries in the app
|
| 24 |
+
min_length=30
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
if summary:
|
| 28 |
+
return summary
|
| 29 |
+
else:
|
| 30 |
+
return "Error: Failed to generate summary. The input may be too short or an issue occurred."
|
| 31 |
+
|
| 32 |
+
# --- 3. Create and configure the Gradio interface ---
|
| 33 |
+
with gr.Blocks() as demo:
|
| 34 |
+
gr.Markdown(
|
| 35 |
+
"""
|
| 36 |
+
# 📝 Text Summarization with Hugging Face
|
| 37 |
+
|
| 38 |
+
This demo uses the `sshleifer/distilbart-cnn-12-6` model to generate a concise summary of a long text document.
|
| 39 |
+
|
| 40 |
+
**How to use:** Paste your text into the "Original Text" box and click "Summarize".
|
| 41 |
+
"""
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
with gr.Row():
|
| 45 |
+
# Input component
|
| 46 |
+
text_input = gr.Textbox(
|
| 47 |
+
lines=15,
|
| 48 |
+
label="Original Text",
|
| 49 |
+
placeholder="Paste a long article or document here..."
|
| 50 |
+
)
|
| 51 |
+
# Output component
|
| 52 |
+
summary_output = gr.Textbox(
|
| 53 |
+
lines=15,
|
| 54 |
+
label="Summarized Text",
|
| 55 |
+
interactive=False
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Button to trigger the summarization
|
| 59 |
+
summarize_button = gr.Button("Summarize")
|
| 60 |
+
|
| 61 |
+
# Connect the button click to the prediction function
|
| 62 |
+
summarize_button.click(
|
| 63 |
+
fn=generate_summary,
|
| 64 |
+
inputs=text_input,
|
| 65 |
+
outputs=summary_output
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# --- 4. Launch the application ---
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
print("Launching Gradio app...")
|
| 71 |
+
# The app will be accessible at a local URL (e.g., http://127.0.0.1:7860)
|
| 72 |
+
demo.launch()
|
level_1_text_summarization.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LEVEL 1, PROJECT 2: TEXT SUMMARIZATION
|
| 2 |
+
# As per the PORTFOLIO_ROADMAP.md, this script demonstrates using a pre-trained
|
| 3 |
+
# pipeline for another common NLP task: text summarization.
|
| 4 |
+
|
| 5 |
+
# Step 1: Ensure required libraries are installed.
|
| 6 |
+
# You can run this command in your terminal:
|
| 7 |
+
# pip install transformers torch
|
| 8 |
+
|
| 9 |
+
# Step 2: Import the pipeline function from the transformers library.
|
| 10 |
+
import torch
|
| 11 |
+
from transformers import pipeline
|
| 12 |
+
|
| 13 |
+
def get_pipeline():
|
| 14 |
+
"""
|
| 15 |
+
Initializes and returns a summarization pipeline, using the GPU if available.
|
| 16 |
+
"""
|
| 17 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 18 |
+
model = "sshleifer/distilbart-cnn-12-6" # A well-known model for summarization
|
| 19 |
+
print(f"Initializing summarization pipeline on device: {'GPU' if device == 0 else 'CPU'}")
|
| 20 |
+
try:
|
| 21 |
+
summarizer = pipeline("summarization", model=model, device=device)
|
| 22 |
+
print("Pipeline initialized successfully.")
|
| 23 |
+
return summarizer
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Failed to initialize the pipeline. Please ensure you have an internet connection.")
|
| 26 |
+
print(f"You may also need to run: pip install transformers torch")
|
| 27 |
+
print(f"Error: {e}")
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
def summarize_text(summarizer, text, max_length=150, min_length=30):
|
| 31 |
+
"""
|
| 32 |
+
Generates a summary for the given text using the provided pipeline.
|
| 33 |
+
"""
|
| 34 |
+
if not summarizer or not text:
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
print("\nPerforming text summarization...")
|
| 38 |
+
try:
|
| 39 |
+
summary = summarizer(text, max_length=max_length, min_length=min_length, do_sample=False)
|
| 40 |
+
return summary[0]['summary_text']
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(f"An error occurred during summarization: {e}")
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
"""
|
| 47 |
+
Main function to run the text summarization process.
|
| 48 |
+
"""
|
| 49 |
+
summarizer = get_pipeline()
|
| 50 |
+
|
| 51 |
+
if summarizer:
|
| 52 |
+
long_text = """
|
| 53 |
+
Hugging Face has emerged as a transformative force in the artificial intelligence
|
| 54 |
+
and machine learning landscape, fundamentally altering how advanced AI technologies
|
| 55 |
+
are developed, accessed, and deployed. The platform's foundational commitment to
|
| 56 |
+
open-source principles has played a pivotal role in democratizing access to
|
| 57 |
+
state-of-the-art models and tools, fostering widespread innovation and collaboration
|
| 58 |
+
across the global AI community. The Hugging Face ecosystem is a meticulously designed
|
| 59 |
+
framework comprising interconnected libraries, a centralized platform, and high-level
|
| 60 |
+
tools, all unified by a steadfast commitment to open-source principles. This
|
| 61 |
+
architecture streamlines the entire machine learning lifecycle, from data preparation
|
| 62 |
+
and model training to deployment and community collaboration. At its core, the
|
| 63 |
+
Transformers library provides access to an extensive collection of pre-trained models,
|
| 64 |
+
while the Datasets library simplifies data handling. The Hub serves as a central
|
| 65 |
+
repository for sharing models, datasets, and interactive applications called Spaces.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
summary_text = summarize_text(summarizer, long_text, max_length=60, min_length=25)
|
| 69 |
+
|
| 70 |
+
if summary_text:
|
| 71 |
+
print("\n--- Text Summarization Results ---")
|
| 72 |
+
print("\nOriginal Text:")
|
| 73 |
+
print(long_text)
|
| 74 |
+
print("\nSummarized Text:")
|
| 75 |
+
print(summary_text)
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers>=4.21.0
|
| 2 |
+
torch>=1.12.0
|
| 3 |
+
gradio>=3.35.0
|
| 4 |
+
huggingface_hub>=0.16.0
|
security_check.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Security check script to ensure no sensitive data is present before pushing to repositories.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
def check_for_sensitive_data():
|
| 11 |
+
"""
|
| 12 |
+
Scans project files for potential sensitive data patterns.
|
| 13 |
+
"""
|
| 14 |
+
sensitive_patterns = [
|
| 15 |
+
r'token\s*=\s*["\'][^"\']+["\']', # token = "value"
|
| 16 |
+
r'password\s*=\s*["\'][^"\']+["\']', # password = "value"
|
| 17 |
+
r'api_key\s*=\s*["\'][^"\']+["\']', # api_key = "value"
|
| 18 |
+
r'secret\s*=\s*["\'][^"\']+["\']', # secret = "value"
|
| 19 |
+
r'hf_[a-zA-Z0-9]{34}', # HuggingFace token pattern
|
| 20 |
+
r'ghp_[a-zA-Z0-9]{36}', # GitHub personal access token
|
| 21 |
+
r'sk-[a-zA-Z0-9]{48}', # OpenAI API key pattern
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
files_to_check = [
|
| 25 |
+
'*.py', '*.md', '*.txt', '*.json', '*.yaml', '*.yml'
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
issues_found = []
|
| 29 |
+
project_root = Path('.')
|
| 30 |
+
|
| 31 |
+
for pattern in files_to_check:
|
| 32 |
+
for file_path in project_root.rglob(pattern):
|
| 33 |
+
# Skip hidden files and cache directories
|
| 34 |
+
if any(part.startswith('.') for part in file_path.parts):
|
| 35 |
+
continue
|
| 36 |
+
if '__pycache__' in str(file_path):
|
| 37 |
+
continue
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 41 |
+
content = f.read()
|
| 42 |
+
|
| 43 |
+
for line_num, line in enumerate(content.splitlines(), 1):
|
| 44 |
+
# Skip comment lines and pattern definitions
|
| 45 |
+
if line.strip().startswith('#') or 'r\'' in line:
|
| 46 |
+
continue
|
| 47 |
+
|
| 48 |
+
for sensitive_pattern in sensitive_patterns:
|
| 49 |
+
if re.search(sensitive_pattern, line, re.IGNORECASE):
|
| 50 |
+
issues_found.append({
|
| 51 |
+
'file': str(file_path),
|
| 52 |
+
'line': line_num,
|
| 53 |
+
'pattern': sensitive_pattern,
|
| 54 |
+
'content': line.strip()
|
| 55 |
+
})
|
| 56 |
+
except (UnicodeDecodeError, PermissionError):
|
| 57 |
+
# Skip binary files or files we can't read
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
return issues_found
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
print("🔍 Scanning for sensitive data in project files...")
|
| 64 |
+
|
| 65 |
+
issues = check_for_sensitive_data()
|
| 66 |
+
|
| 67 |
+
if not issues:
|
| 68 |
+
print("✅ No sensitive data patterns detected!")
|
| 69 |
+
print("✅ Project is safe to push to public repositories.")
|
| 70 |
+
return True
|
| 71 |
+
else:
|
| 72 |
+
print(f"⚠️ Found {len(issues)} potential sensitive data issues:")
|
| 73 |
+
for issue in issues:
|
| 74 |
+
print(f" 📁 {issue['file']}:{issue['line']}")
|
| 75 |
+
print(f" Pattern: {issue['pattern']}")
|
| 76 |
+
print(f" Content: {issue['content'][:80]}{'...' if len(issue['content']) > 80 else ''}")
|
| 77 |
+
print()
|
| 78 |
+
|
| 79 |
+
print("❌ Please review and remove sensitive data before pushing!")
|
| 80 |
+
return False
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
main()
|
tests/test_text_summarization.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from unittest.mock import patch
|
| 3 |
+
from transformers.pipelines.text2text_generation import SummarizationPipeline
|
| 4 |
+
from level_1_text_summarization import get_pipeline, summarize_text
|
| 5 |
+
|
| 6 |
+
class TestTextSummarization(unittest.TestCase):
|
| 7 |
+
|
| 8 |
+
def test_get_pipeline(self):
|
| 9 |
+
"""
|
| 10 |
+
Tests if the get_pipeline function returns a valid summarization pipeline.
|
| 11 |
+
"""
|
| 12 |
+
with patch('level_1_text_summarization.pipeline') as mock_pipeline:
|
| 13 |
+
# Mock the pipeline call to avoid actual model loading during tests
|
| 14 |
+
mock_pipeline.return_value = "MockedPipeline"
|
| 15 |
+
summarizer = get_pipeline()
|
| 16 |
+
# We check if the function returns what the mocked pipeline returned.
|
| 17 |
+
# In a more complex scenario, we would assert its type.
|
| 18 |
+
self.assertIsNotNone(summarizer)
|
| 19 |
+
self.assertIsInstance(summarizer, str) # In this mocked case, it's a string.
|
| 20 |
+
|
| 21 |
+
@patch('level_1_text_summarization.get_pipeline')
|
| 22 |
+
def test_summarize_text(self, mock_get_pipeline):
|
| 23 |
+
"""
|
| 24 |
+
Tests the summarize_text function for basic functionality.
|
| 25 |
+
"""
|
| 26 |
+
# Mock the pipeline object itself
|
| 27 |
+
class MockSummarizer:
|
| 28 |
+
def __call__(self, text, max_length, min_length, do_sample):
|
| 29 |
+
return [{'summary_text': 'This is a test summary.'}]
|
| 30 |
+
|
| 31 |
+
mock_summarizer_instance = MockSummarizer()
|
| 32 |
+
|
| 33 |
+
# The text to be summarized
|
| 34 |
+
sample_text = "This is a long piece of text that needs to be summarized for a unit test."
|
| 35 |
+
|
| 36 |
+
# Call the function with the mocked summarizer
|
| 37 |
+
summary = summarize_text(mock_summarizer_instance, sample_text)
|
| 38 |
+
|
| 39 |
+
# Assert that the summary is a non-empty string
|
| 40 |
+
self.assertIsInstance(summary, str)
|
| 41 |
+
self.assertTrue(len(summary) > 0)
|
| 42 |
+
self.assertEqual(summary, 'This is a test summary.')
|
| 43 |
+
|
| 44 |
+
def test_summarize_text_with_none_pipeline(self):
|
| 45 |
+
"""
|
| 46 |
+
Tests that summarize_text returns None if the pipeline is not available.
|
| 47 |
+
"""
|
| 48 |
+
summary = summarize_text(None, "Some text")
|
| 49 |
+
self.assertIsNone(summary)
|
| 50 |
+
|
| 51 |
+
if __name__ == '__main__':
|
| 52 |
+
unittest.main()
|
upload_to_hub.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from huggingface_hub import HfApi, HfFolder
|
| 3 |
+
|
| 4 |
+
def upload_project_to_hub():
|
| 5 |
+
"""
|
| 6 |
+
Uploads the complete project to a specified Hugging Face Hub repository.
|
| 7 |
+
"""
|
| 8 |
+
# --- Configuration ---
|
| 9 |
+
# NOTE: Ensure you are logged in via `huggingface-cli login` in your terminal first.
|
| 10 |
+
# The token will be read automatically from the local cache.
|
| 11 |
+
repo_id = "ArtemisAI/Level-1-Project-2-Text-Summarization"
|
| 12 |
+
project_directory = "."
|
| 13 |
+
|
| 14 |
+
print(f"Preparing to upload project to Hugging Face Hub repository: {repo_id}")
|
| 15 |
+
|
| 16 |
+
api = HfApi()
|
| 17 |
+
|
| 18 |
+
# 1. Create the repository on the Hub (if it doesn't exist)
|
| 19 |
+
try:
|
| 20 |
+
api.create_repo(
|
| 21 |
+
repo_id=repo_id,
|
| 22 |
+
repo_type="space", # This is a Gradio Space
|
| 23 |
+
space_sdk="gradio",
|
| 24 |
+
exist_ok=True,
|
| 25 |
+
)
|
| 26 |
+
print(f"Repository '{repo_id}' created or already exists.")
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"Error creating repository: {e}")
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
# 2. Upload the entire project folder
|
| 32 |
+
# The HfApi().upload_folder function will handle all files recursively.
|
| 33 |
+
try:
|
| 34 |
+
print(f"Uploading contents of '{project_directory}' to '{repo_id}'...")
|
| 35 |
+
api.upload_folder(
|
| 36 |
+
folder_path=project_directory,
|
| 37 |
+
repo_id=repo_id,
|
| 38 |
+
repo_type="space",
|
| 39 |
+
# Ignore git files, pycache, and other local artifacts
|
| 40 |
+
allow_patterns=["*.py", "*.md", "*.txt"],
|
| 41 |
+
ignore_patterns=["*.git*", "*__pycache__*"],
|
| 42 |
+
)
|
| 43 |
+
print("✅ Upload complete!")
|
| 44 |
+
print(f"Check out your Space here: https://huggingface.co/spaces/{repo_id}")
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"An error occurred during the upload: {e}")
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
# Ensure a token is available for authentication
|
| 50 |
+
if HfFolder.get_token() is None:
|
| 51 |
+
print("Hugging Face token not found.")
|
| 52 |
+
print("Please log in using the 'huggingface-cli login' command in your terminal.")
|
| 53 |
+
else:
|
| 54 |
+
upload_project_to_hub()
|