LANG: text_____ _ _____ _ _ _ _ _ _ _____ |_ _|____ _| |_|_ _| (_) | | | | | \ | | | | __ \ | | / _ \ \/ / __|| | _ __ ___ _ __ _| |__ | |_ | \| | | | |__) | | || __/> <| |_ | | | '_ \/ __| |/ _` | '_ \| __| | . ` | | | ___/ | | \___/_/\_\\__||_| | | | \__ \ | (_| | | | | |_ | |\ | |___| | \_/ |_| |_|___/_|\__, |_| |_|\__| \_| \_\_____/_| __/ | |___/
TextInsight-NLP
Unlock the Hidden Value of Unstructured Text Data with Production-Grade Python Analysis
Project Type: NLP Pipeline & API Library / Local Analytics Engine
Industry Domain: Data Science, Artificial Intelligence, Educational Technology
Target Audience: Researchers, Students, Data Scientists, Software Engineers
Primary Purpose: To automate and scale the extraction of insights (sentiment, keywords, entities, summarization, readability) from large volumes of unstructured text.
π Developer Message
"Welcome to TextInsight-NLP. As an individual navigating a complex academic landscape, I realized how much time is lost manually parsing articles, feedback forms, and research papers. I built TextInsight-NLP not just as a semester project, but as a foundational library that can grow into a formidable tool for anyone overwhelmed by text. It is designed with modularity, clean architecture, and extensibility in mind. I hope this tool saves you as much time as it has saved me."
β Godfrey T R, Lead Developer & Maintainer
π Developer Story
Why I Built It
The digital age produces an unfathomable amount of text data every single day. From academic research to customer feedback, the answers to many of our most pressing questions are buried in unstructured paragraphs. Manually reading, summarizing, and extracting key information is not only time-consuming but highly susceptible to cognitive fatigue and human bias. As a student and developer, I constantly faced the challenge of synthesizing large academic papers. There was a critical need for an automated, reliable system to process and derive meaning from text rapidly, without relying entirely on expensive cloud APIs. Thus, TextInsight-NLP was born.
Who I Am
This project was developed by Godfrey T R as an individual semester project. It represents a synthesis of computer science fundamentals, software engineering best practices, and applied data science.
Challenges Faced
Building a production-grade NLP system locally presented several hurdles:
- Dependency Hell: Harmonizing different versions of NLTK, Scikit-learn, and SciPy to ensure stable cross-platform performance. The Python package ecosystem can be fragile when dealing with native C-bindings used by scientific libraries.
- Performance vs. Accuracy: Balancing the need for rapid real-time processing with the computational overhead of advanced tasks like Topic Discovery (NMF/LDA) and Named Entity Recognition. I had to implement lazy loading and conditional pipeline execution.
- Architecture: Ensuring the system was highly modular so future maintainers (or myself) could drop in new models (e.g., HuggingFace transformers) without breaking the existing pipeline.
- Data Structures: Moving away from standard dictionaries to strongly typed
Pydantic-style dataclasses to ensure the engine always outputs predictable formats.
How I Built It
I adopted a modular processor-based architecture. Instead of monolithic scripts, the text passes through a configured pipeline of isolated Processor classes (Cleaning, Tokenization, Syntax, Sentiment, Keywords). This was built strictly in Python to leverage the rich data science ecosystem. pytest was integrated from day one to ensure high reliability. The entire system is built on the Chain of Responsibility design pattern.
Security & UX
Even for a local CLI/Library, security and user experience are paramount:
- UX: The CLI is highly interactive, gracefully handles empty inputs, and formats rich output natively.
- Security: Strict memory limits are implied. File parsers (like PyPDF2) are sandboxed to prevent malicious file execution. No user data is ever transmitted to a third-party serverβeverything runs 100% locally on your machine.
Key Learnings
- Pipeline Design Patterns: Implementing the Chain of Responsibility pattern for NLP text processing yields the cleanest code.
- Lexical Analysis Limits: While TF-IDF and NLTK rule-based systems are lightning-fast, they lack the contextual nuance of deep learning. This project set the perfect stage for future transformer integrations.
- Testing Data Science Code: Learning to write deterministic tests for probabilistic and heuristic algorithms was a major growth area.
Future Roadmap
- v2.0 (Transformer Integration): Optional HuggingFace integration for state-of-the-art NER and sentiment using BERT or RoBERTa.
- v2.5 (REST API): Wrapping the core engine in a FastAPI shell for network deployment, enabling microservices architecture.
- v3.0 (Web UI): A React-based dashboard for drag-and-drop document analysis.
- v4.0 (Distributed Processing): Adding Celery or Apache Kafka support to process millions of documents asynchronously.
π Table of Contents
- System Architecture
- Features & Capabilities
- Technology Stack
- Folder Structure
- Getting Started
- Usage Guide
- API Documentation
- Configuration
- Advanced Workflows
- Deployment Instructions
- Scalability Considerations
- Security & Privacy
- Testing & Quality Assurance
- Troubleshooting & FAQs
- Contributing
- Acknowledgments
- License
π System Architecture
The architecture of TextInsight-NLP is designed around a decoupled pipeline. Text flows through a series of "Processors", each responsible for a specific NLP task, accumulating data into a central AnalysisResult object. This ensures maximum testability and extensibility.
High-Level Architecture Diagram
LANG: mermaidgraph TD A[Input Source: String/File] --> B(analyze_text wrapper) B --> C{Pipeline Engine} subgraph Processor Pipeline C --> D[Cleaning Processor] D --> E[Tokenization Processor] E --> F[Syntax Processor] F --> G[Sentiment Processor] G --> H[Keyword Processor] H --> I[NER Processor] I --> J[Statistics & Readability] end J --> K[AnalysisResult Model] K --> L[Output Formatting] L --> M((CLI Display)) L --> N((JSON / Dict))
Processor Execution Sequence
LANG: mermaidsequenceDiagram participant User participant CLI participant Engine participant Processors participant Model User->>CLI: Enter text / Submit file CLI->>Engine: analyze_text(raw_data) Engine->>Model: Instantiate AnalysisResult() Engine->>Processors: Execute Cleaning Processors-->>Model: Update cleaned_text Engine->>Processors: Execute Tokenization/Syntax Processors-->>Model: Update tokens, sentences Engine->>Processors: Execute Advanced (Sentiment, Keywords) Processors-->>Model: Update polarity, topics, etc. Engine-->>CLI: Return Result Dictionary CLI-->>User: Formatted Output / Terminal Print
Data Flow Architecture
LANG: mermaidgraph LR A[Raw Text Input] --> B(Cleaning Engine); B --> C{Sanitized Text}; C --> D(Tokenization); C --> E(Sentence Splitting); D --> F{Tokens Array}; E --> G{Sentences Array}; F --> H(Keyword TF-IDF); F --> I(Part of Speech Tagging); G --> J(Sentiment Engine); G --> K(Summarization Engine); I --> L(Named Entity Recognition); H --> M((Output Formatting)); J --> M; K --> M; L --> M;
β¨ Features & Capabilities
TextInsight-NLP is not just a simple word counter. It is a comprehensive text analytics engine.
| Feature Area | Description | Implementation Details |
|---|---|---|
| Text Cleaning | Removes noise, normalizes spacing, strips HTML, and handles encoding. | Regex-based cleaning, Unicode normalization, handling of non-printable characters. |
| Tokenization & POS | Breaks text into words, sentences, and applies Part-of-Speech tags. | Utilizes nltk.word_tokenize and nltk.pos_tag with the Averaged Perceptron tagger. |
| Sentiment Analysis | Determines emotional tone (Polarity) and subjectivity. | textblob.TextBlob underlying engine mapping polarity onto a standard -1.0 to 1.0 scale. |
| Keyword Extraction | Identifies the most mathematically significant words. | Scikit-learn TfidfVectorizer ignoring common stop words and using n-gram extraction. |
| Topic Discovery | Clusters text into thematic topics using matrix factorization. | Scikit-learn NMF (Non-Negative Matrix Factorization) operating on term-frequency matrices. |
| Readability Metrics | Calculates Flesch Reading Ease and Kincaid Grade Levels. | Custom syllabic counting and sentence length algorithms tailored for english phonetics. |
| Named Entity Recognition | Extracts Persons, Organizations, and Locations from text. | nltk.ne_chunk mapping tree structures into flat JSON arrays. |
| Extractive Summarization | Condenses text to key sentences based on word frequency scoring. | Custom frequency-scoring algorithm ranking sentence weight. |
π Technology Stack
Core Technologies
- Programming Language: Python 3.9+
- Architecture Paradigm: Object-Oriented, Pipeline Pattern, Type Hinting
Data Science & NLP Libraries
- NLTK (Natural Language Toolkit): The backbone for tokenization, POS tagging, and NER.
- TextBlob: Utilized for rapid, lexicon-based sentiment analysis and translation routing.
- Scikit-Learn: Powers the TF-IDF vectorizers for keyword extraction and topic modeling.
- NumPy & SciPy: Underlying mathematical operations for matrix factorization.
- LangDetect: Robust multi-language identification.
Utility & Infrastructure
- PyPDF2 & pypdf: For parsing and extracting text from PDF document inputs securely.
- Pytest: Comprehensive unit and integration testing framework.
- Black: Code formatting.
π Folder Structure
LANG: textTextInsight-NLP/ β βββ text_insight/ # Core Package Directory β βββ __init__.py # Package exports and main wrapper β βββ config.py # NLPConfig data class definition β βββ models.py # AnalysisResult data models β βββ exceptions.py # Custom exception definitions β β β βββ core/ # Engine Mechanics β β βββ __init__.py β β βββ engine.py # Pipeline orchestrator β β βββ processor.py # Base interface for processors β β β βββ processors/ # Individual NLP Modules β β βββ __init__.py β β βββ cleaning.py # Removes noise β β βββ keywords.py # TF-IDF extraction β β βββ sentiment.py # TextBlob wrapper β β βββ syntax.py # Sentences and readability β β βββ tokenization.py # Word splitting and POS β β β βββ utils/ # Helper functions β βββ file_handlers.py # PDF and TXT reading utilities β βββ tests/ # Pytest Test Suite β βββ test_cleaning.py # Validates regex β βββ test_sentiment.py # Validates polarity scoring β βββ test_engine.py # Validates full pipeline β βββ ... β βββ web_gui/ # Simulation Web Interface β βββ index.html # UI structure β βββ style.css # UI styling (glassmorphism) β βββ script.js # Terminal simulation logic β βββ main.py # Legacy / Standard CLI Entry Point βββ example.py # API Usage Examples βββ start.bat # Windows initialization script βββ requirements.txt # Dependency definitions βββ README.md # This documentation
π Getting Started
Prerequisites
- Operating System: Windows 10/11, macOS, or Linux (Ubuntu/Debian preferred).
- Python: Version 3.9, 3.10, 3.11, or 3.12 installed and added to PATH.
- Memory: Minimum 4GB RAM (8GB+ recommended for large document analysis).
- Disk Space: ~500MB free for NLP corpora downloads.
Installation
-
Clone the Repository Using Git, clone the codebase to your local machine.
LANG: bashgit clone https://github.com/GodfreyTR/TextInsight-NLP.git cd TextInsight-NLP -
Create a Virtual Environment (Highly Recommended) Isolate your project dependencies from the global Python environment.
LANG: bashpython -m venv venv # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate -
Install Dependencies Install the robust suite of data science packages.
LANG: bashpip install --upgrade pip pip install -r requirements.txt -
Download Required NLTK Data The system requires specific NLTK corpora to function. Run the initialization script or do it manually:
LANG: bashpython -c "import nltk; nltk.download('punkt'); nltk.download('averaged_perceptron_tagger'); nltk.download('maxent_ne_chunker'); nltk.download('words'); nltk.download('wordnet')"(Note: The
start.batscript on Windows handles this automatically).
π» Usage Guide
CLI Usage
The simplest way to use TextInsight-NLP is via the command line interface. The interface provides a rich, formatted output summarizing the analysis of your text block.
On Windows:
Simply double-click start.bat or run:
LANG: cmdstart.bat
Cross-Platform:
LANG: bashpython main.py
Example Output:
LANG: text----- TEXT ANALYZER ----- Enter the text to analyze: The new quantum computing breakthroughs at MIT are absolutely phenomenal. However, the energy consumption remains a terrible problem. Detected Language: en Tokens Count: 23 Sentiment Analysis: Polarity: 0.125 Subjectivity: 0.650 Label: POSITIVE Identified Keywords: ['quantum', 'breakthroughs', 'phenomenal', 'energy', 'consumption']
Programmatic Usage (Python API)
You can easily integrate TextInsight-NLP into your own Python applications. The codebase is heavily typed, making it IDE friendly.
LANG: pythonfrom text_insight import analyze_text, NLPConfig # 1. Standard usage with default config text = "Apple Inc. announced record profits in California today. The market responded positively." result = analyze_text(text) # Access rich data points print(f"Sentiment: {result.sentiment.polarity}") print(f"Reading Level: {result.readability['flesch_kincaid_grade']}") for entity in result.entities: print(f"Found Entity: {entity['text']} ({entity['label']})") # 2. Custom Configuration custom_config = NLPConfig( language="en", num_keywords=5, keyword_strategy="tfidf", enable_ner=True, enable_topic_modeling=False # Disable for speed ) fast_result = analyze_text(text, config=custom_config)
π API Documentation
Core Methods
text_insight.analyze_text(text: str, config: NLPConfig = None) -> AnalysisResult
The primary wrapper function that orchestrates the pipeline.
Parameters:
text(str): The raw string to be analyzed. Must be a valid utf-8 string.config(NLPConfig, optional): Configuration object to tune the pipeline. Defaults to a standardNLPConfigif none is provided.
Returns:
AnalysisResult: A dataclass containing all derived metrics.
Raises:
TextProcessingError: If the pipeline crashes due to invalid input.
NLPConfig Dataclass
Controls the behavior of the engine. Defined in config.py.
| Parameter | Type | Default | Description |
|---|---|---|---|
language | str | "auto" | Forces a specific language (e.g., "en") or auto-detects. |
num_keywords | int | 10 | Number of keywords to extract. |
keyword_strategy | str | "tfidf" | "tfidf" or "frequency". TF-IDF is better for large texts, while frequency works well for tiny texts. |
summary_ratio | float | 0.3 | Percentage of sentences to keep in the extractive summary. Range 0.0 to 1.0. |
enable_ner | bool | True | Whether to run Named Entity Recognition (can be slow on massive texts). |
enable_topic_modeling | bool | True | Whether to run NMF topic modeling (requires minimum 5 sentences usually). |
AnalysisResult Dataclass
The ultimate artifact produced by the pipeline. Contains nested dictionaries and lists containing the exact mathematical outputs.
Properties:
raw_text(str): The unmodified original string.cleaned_text(str): The sanitized string used for processing.language(str): The detected language code (e.g., 'en').tokens(List[str]): List of words.lemmas(List[str]): List of lemmatized words.sentences(List[str]): List of sentence strings.pos_tags(List[Tuple[str, str]]): List of(word, POS_TAG)pairs.sentiment(Dict): Object withpolarity(float),subjectivity(float),label(str), andconfidence(float).keywords(List[str]): Extracted keywords.entities(List[Dict]): List of dictionaries{"text": str, "label": str, "start_char": int, "end_char": int}readability(Dict): Dictionary of scores includingflesch_reading_ease,flesch_kincaid_grade.summary(str): String containing the extractive summary.topics(List[Dict]): Nested dictionary containing topics and associated top words.statistics(Dict): Dictionary of word counts, chars, and reading time.
Methods:
.to_dict(): Recursively serializes the object to a standard Python dictionary, ready for JSON conversion.
βοΈ Configuration Examples
You can fine-tune the engine for different use cases. Because NLP tasks scale exponentially with text length, adjusting config is vital for large workloads.
Configuration: High-Speed Preprocessing
When processing millions of tweets or short reviews, disable slow tasks.
LANG: pythonfrom text_insight import NLPConfig, analyze_text speed_config = NLPConfig( enable_ner=False, enable_topic_modeling=False, num_keywords=3, keyword_strategy="frequency" # Faster than TF-IDF matrices ) result = analyze_text("This product is amazing!", config=speed_config)
Configuration: Deep Academic Research
When analyzing PDFs of research papers, maximize insights.
LANG: pythondeep_config = NLPConfig( num_keywords=25, keyword_strategy="tfidf", summary_ratio=0.15, # Distill heavy text down heavily enable_topic_modeling=True ) result = analyze_text(heavy_academic_text, config=deep_config)
π Advanced Workflows
Bulk Document Processing
If you need to process a directory of files, use the pipeline efficiently. The engine can handle loop processing efficiently.
LANG: pythonimport os import json from text_insight import analyze_text, NLPConfig config = NLPConfig(enable_ner=False) results = [] for filename in os.listdir('./data'): if filename.endswith('.txt'): with open(os.path.join('./data', filename), 'r', encoding='utf-8') as f: content = f.read() res = analyze_text(content, config=config) results.append({ "file": filename, "sentiment": res.sentiment['label'], "summary": res.summary }) with open('report.json', 'w') as out: json.dump(results, out, indent=4)
PDF Processing Pipeline
You can extract text from a PDF and feed it directly into the engine.
LANG: pythonfrom pypdf import PdfReader from text_insight import analyze_text reader = PdfReader("research_paper.pdf") text = "" for page in reader.pages: text += page.extract_text() + "\n" result = analyze_text(text) print(result.keywords)
π Deployment Instructions
While designed as a library, TextInsight-NLP can be deployed as a microservice in an enterprise environment.
Deploying as a REST API (using FastAPI)
You can easily wrap this engine in FastAPI for a production web service:
-
Install FastAPI & Uvicorn
LANG: bashpip install fastapi uvicorn pydantic -
Create
app.pyLANG: pythonfrom fastapi import FastAPI from pydantic import BaseModel from text_insight import analyze_text app = FastAPI(title="TextInsight NLP Service", version="1.0") class TextRequest(BaseModel): text: str config: dict = None @app.post("/api/v1/analyze") async def analyze(request: TextRequest): # Map dict config to NLPConfig if needed result = analyze_text(request.text) return result.to_dict() -
Run Server
LANG: bashuvicorn app:app --host 0.0.0.0 --port 8000 --workers 4 -
Containerization (Docker) Create a
Dockerfilefor Kubernetes or Docker Swarm deployment:LANG: dockerfileFROM python:3.10-slim # Set working directory WORKDIR /app # Copy dependencies COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Pre-download NLTK models to bake into the image RUN python -c "import nltk; nltk.download('punkt'); nltk.download('averaged_perceptron_tagger'); nltk.download('maxent_ne_chunker'); nltk.download('words'); nltk.download('wordnet')" # Copy application source COPY . . # Expose port EXPOSE 8000 # Start Uvicorn Server CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
π Scalability Considerations
When scaling TextInsight-NLP in an enterprise environment, consider the following:
- CPU Bound Nature: NLP processing is heavily CPU-bound. If deploying as a web API, use multi-processing (e.g., Uvicorn workers or Gunicorn processes) rather than multi-threading. Threads in Python (due to the GIL) will not speed up matrix math effectively.
- Memory Profiling: Scikit-learn's TF-IDF vectorizer builds dense matrices. For documents exceeding 50MB (like a database dump), consider chunking the document into paragraphs before processing to avoid
MemoryError. - Stateless Architecture: The
PipelineEngineis completely stateless. It does not store user data internally. It can be instantiated once per worker process and reused safely across millions of requests without memory leaks. - Caching Strategy: If the same documents are analyzed frequently (e.g., analyzing standard company policies), implement a Redis caching layer using a SHA-256 hash of the text content as the cache key.
- Horizontal Scaling: Because it is stateless, you can spin up 100 docker containers behind an AWS Application Load Balancer and it will scale perfectly linearly.
π Security & Privacy
TextInsight-NLP takes data privacy seriously.
- 100% Local Execution: By default, no text data is sent to external APIs (like OpenAI, Google Cloud, or AWS Comprehend). All processing happens entirely on your local CPU. It is GDPR and HIPAA compliant out of the box because data never leaves the machine.
- Data Retention: The pipeline does not log or store the text it processes. Memory is freed immediately after the
AnalysisResultis garbage collected by Python. - Input Sanitization: The
CleaningProcessoractively strips zero-width characters, null bytes, and normalizes Unicode to prevent rendering exploits or parser crashes further down the pipeline. - Dependency Auditing: Dependencies are kept minimal to reduce the supply chain attack surface.
π§ͺ Testing & Quality Assurance
TextInsight-NLP uses pytest for robust test coverage, ensuring enterprise-grade reliability.
Running the Test Suite
Ensure you have pytest installed, then run from the root directory:
LANG: bashpytest tests/ -v
To run with coverage (requires pytest-cov):
LANG: bashpytest tests/ --cov=text_insight --cov-report=html
Test Coverage Areas
- Unit Tests: Isolated tests for
CleaningProcessor,SentimentProcessor, verifying regex boundaries and mathematical assertions. - Integration Tests: Verifying the data flows correctly through the
PipelineEnginefrom raw string to finalAnalysisResult. - Edge Cases: Testing with empty strings, extremely long strings, strings with emojis, and non-English text to ensure graceful fallbacks and no uncaught exceptions.
β Troubleshooting & FAQs
Q: I'm getting an nltk Resource Lookup Error.
A: You haven't downloaded the required NLTK datasets. Run start.bat on Windows, or execute python -m nltk.downloader all to download everything.
Q: The Topic Discovery feature is returning empty or nonsensical topics.
A: Topic discovery requires a decent amount of text. If you feed it a single 10-word sentence, matrix factorization will fail to find meaningful clusters. Provide at least a few paragraphs.
Q: How do I make sentiment analysis more accurate?
A: The current system uses TextBlob (lexicon-based). For higher accuracy, you can subclass Processor and integrate a HuggingFace Transformer model in the pipeline.
Q: MemoryError when analyzing a 500-page book.
A: Read the book in chunks (e.g., chapter by chapter) and analyze them iteratively rather than loading 500 pages into the matrix factorization engine at once.
Q: Can I use this for non-English languages?
A: The engine attempts to detect language. Basic features like tokenization work for many languages, but advanced features like Readability and Sentiment are heavily optimized for English. Expect degraded accuracy for other languages currently.
π€ Contributing
Contributions are what make the open-source community such an amazing place to learn, inspire, and create.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Please ensure that your code adheres to standard Python PEP 8 styling and that all pytest checks pass.
π Acknowledgments
- NLTK Community: For building the foundational tools of Python NLP.
- TextBlob: For making sentiment analysis incredibly accessible.
- Scikit-Learn: For providing robust machine learning algorithms out of the box.
- Open Source Supporters: Everyone who believes in free, local, accessible AI and NLP software.
π License
Distributed under the MIT License. See LICENSE for more information.