Merge pull request 'chore: remove dev artifacts, fix hardcoded path, add tests + license' (#8) from improve/v1
Some checks are pending
CI / lint (push) Waiting to run
CI / test (push) Waiting to run
CI / docker-build (push) Waiting to run
CI / security (push) Waiting to run
CI / build-result (push) Blocked by required conditions

This commit is contained in:
Jarian Cottingham 2026-08-20 21:39:25 +00:00
commit 8030ef8efe
28 changed files with 379 additions and 886 deletions

BIN
.DS_Store vendored

Binary file not shown.

6
.gitignore vendored
View File

@ -24,3 +24,9 @@ nohup.out
*.pyc
*.log
.DS_Store
pyvenv.cfg
processed_articles_cache.json

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Jarian Cottingham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,7 +1,6 @@
import chromadb
from flask import Flask, request, jsonify, send_from_directory
import os
import json
import requests
import logging
from datetime import datetime

View File

@ -131,9 +131,19 @@ docker run -p 5008:5008 stockdocs-article-server
# Continue for other components...
```
## Tests
```bash
pip install -r scraper/requirements_clean.txt pytest
pytest tests/ -v
```
Unit tests cover the scraper's article-processing cache: load/save
roundtrips, processing status tracking, and progress computation.
## Requirements
- Python 3.6+
- Python 3.9+
- Flask 2.3.3
- Various NLP and ML libraries
- Docker (for containerized deployment)

277
agent
View File

@ -1,277 +0,0 @@
# StockDocs Project Overview
This document provides a comprehensive overview of the StockDocs financial news analysis platform, including detailed information about each project component, file structures, and how to begin working with the system.
## Project Architecture
StockDocs is a sophisticated system designed to collect, process, and analyze financial news from multiple sources. The platform consists of several interconnected components that work together to transform raw news content into valuable market intelligence.
```
+--------------+ +--------------+ +-------------------+
| Scraper | | Article | | AI |
| (RSS Feeds) |--> | Server |--> | Processor |
| | | | | |
+--------------+ +--------------+ +-------------------+
| |
v v
+--------------+ +-------------------+
| Embedding | | MCPServer |
| Service | | (Financial Data) |
| | | |
+--------------+ +-------------------+
```
## Project Components
### 1. Scraper
**Location:** `scraper/`
The Scraper component is responsible for collecting financial news and articles from multiple sources including major news outlets, financial publications, and market analysis services. It uses RSS feeds to gather content and stores the articles in a structured directory hierarchy for easy access by other components of the system.
#### Key Features:
- RSS Feed Integration: Supports multiple financial news sources through RSS feeds
- Automated Scraping: Regularly fetches and processes new articles from configured feeds
- Structured Storage: Organizes articles in a directory structure by news outlet
- Duplicate Detection: Prevents re-processing of already collected articles
- Caching Mechanism: Maintains a cache of processed articles to optimize performance
#### File Structure:
```
scraper/
├── rss_feeds.json # Configuration file with RSS feed URLs
├── scraper.py # Main scraping logic
├── requirements.txt # Python dependencies
├── dockerfile # Docker configuration
├── dockerfile-selenium # Dockerfile for selenium-based scraping
├── articles/ # Directory where scraped articles are stored
│ ├── Reuters Business News/
│ │ ├── article1.txt
│ │ └── ...
│ ├── Associated Press Business/
│ │ ├── article1.txt
│ │ └── ...
│ └── ...
├── processed_articles_cache.json # Cache of already processed articles
└── pyvenv.cfg # Python virtual environment configuration
```
#### Key Files:
- `scraper.py`: Main scraping logic with parallel processing capabilities
- `rss_feeds.json`: Configuration file with RSS feed URLs for 60+ news outlets
- `articles/`: Directory structure for storing scraped articles organized by news source
### 2. Article Server
**Location:** `articleServer/`
A Flask-based HTTP server that provides access to news articles stored in a directory structure, with time-based filtering and outlet-specific querying capabilities.
#### Key Features:
- Time-based filtering: Query articles by hour, day, week, or month
- Outlet-specific querying: Filter articles by news source
- Content retrieval: Get full article content by file path
- RESTful API: Clean interfaces for integration with external systems
#### File Structure:
```
articleServer/
├── app.py # Main Flask application
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── run_server.py # Server startup script
├── pyvenv.cfg # Python virtual environment configuration
└── README.md # Documentation
```
#### API Endpoints:
- `GET /articles` - Get articles within time range
- `GET /article/content` - Get full article content by path
- `GET /outlets` - List all available news outlets
- `GET /health` - Health check endpoint
### 3. AI Processor
**Location:** `ai_processor/`
An AI-powered analytics engine designed to process financial news articles and extract meaningful insights, sentiment analysis, and market indicators from collected content.
#### Key Features:
- Sentiment Analysis: Determine positive, negative, or neutral sentiment of news articles
- Topic Classification: Categorize articles by financial topics
- Entity Extraction: Identify key entities mentioned in articles (stocks, companies, people, organizations)
- Market Indicator Detection: Extract quantitative indicators that may affect stock prices
- Insight Generation: Automated generation of actionable intelligence from news content
- Batch Processing: Process large volumes of articles efficiently
#### File Structure:
```
ai_processor/
├── ai_processor.py # Main AI processing application
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── README.md # Documentation
├── models/ # Machine learning models and NLP components
│ ├── sentiment_analyzer.py # Sentiment analysis module
│ ├── topic_classifier.py # News categorization module
│ └── entity_extractor.py # Named entity recognition
├── processors/ # Article processing pipelines
│ ├── text_processor.py # Text cleaning and preprocessing
│ └── analysis_pipeline.py # Full analysis pipeline
└── output/ # Processed data storage
├── insights/
└── reports/
```
#### API Endpoints:
- `POST /api/analyze/article` - Analyze a single article for insights
- `POST /api/analyze/batch` - Process multiple articles in batch mode
- `GET /api/insights/latest` - Get latest analysis insights
- `GET /api/models` - List available AI models
### 4. Embedding Service
**Location:** `embedding/`
An embedding service that converts text content into numerical vectors for machine learning and data analysis purposes. This component transforms financial news articles into vector representations that can be used for similarity comparisons, clustering, and other AI tasks.
#### Key Features:
- Multiple Model Support: Integrates with various embedding models including BERT, Sentence-BERT, and other transformer-based models
- Batch Processing: Efficient processing of large volumes of articles
- Caching Mechanism: Caches generated embeddings to avoid reprocessing
- Real-time Generation: Generates embeddings on-demand for new content
- Vector Similarity: Computes similarity between different pieces of content
- Storage Management: Organizes and stores embeddings efficiently
#### File Structure:
```
embedding/
├── embedder.py # Main embedding application
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── README.md # Documentation
├── models/ # Pre-trained embedding models
│ ├── sentence_transformer.py # Sentence transformer implementation
│ └── model_loader.py # Model loading utilities
├── processors/ # Text processing pipeline
│ ├── text_cleaner.py # Text cleaning and preprocessing
│ └── embedding_generator.py # Embedding generation
└── data/ # Processed embeddings storage
├── cache/
└── outputs/
```
#### API Endpoints:
- `POST /api/embeddings/generate` - Generate embeddings for text content
- `POST /api/embeddings/batch` - Generate embeddings for multiple texts in batch
- `GET /api/embeddings/similarity` - Calculate similarity between two pieces of text/content
### 5. MCPServer
**Location:** `MCPServer/`
A Flask-based server that provides an API for accessing and analyzing financial data, with integration for stock analysis and news processing. Serves as the backend service for processing financial information and making it available through HTTP endpoints.
#### Key Features:
- Stock Analysis: Financial metrics calculation and market data processing
- News Integration: APIs for retrieving and processing financial news
- Data Aggregation: Consolidation of multiple data sources into unified responses
- RESTful API: Clean HTTP interface for external services to consume data
#### File Structure:
```
MCPServer/
├── server.py # Main Flask application
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── openapi.json # API specification
├── README.md # Documentation
└── api/ # API endpoints and handlers
├── stock_analysis.py # Stock analysis functions
└── news_processing.py # News processing functions
```
#### API Endpoints:
- `POST /query` - Query the vector database with a question
- `GET /health` - Server health check
- `GET /info` - Returns model and service metadata
- `GET /tools` - List available endpoints and their descriptions
## Setup and Installation
### Prerequisites
- Python 3.6+
- Docker (for containerized deployment)
- Internet connection for RSS feed access
### Installation Steps
1. **Clone the repository:**
```bash
git clone <repository-url>
cd StockDocs
```
2. **Set up each component:**
```bash
# For each component, follow specific installation instructions
cd scraper && pip install -r requirements.txt
cd articleServer && pip install -r requirements.txt
cd ai_processor && pip install -r requirements.txt
cd embedding && pip install -r requirements.txt
cd MCPServer && pip install -r requirements.txt
```
3. **Configure environment variables as needed for each component**
4. **Run individual services:**
```bash
python scraper/scraper.py # Start scraping
python articleServer/run_server.py # Start article server
python ai_processor/app.py # Start AI processor
python embedding/app.py # Start embedding service
python MCPServer/app.py # Start MCP server
```
## Deployment
Each component can be run independently or containerized using the provided Dockerfiles:
```bash
# Build and run each component in Docker
docker build -t stockdocs-scraper ./scraper
docker run -p 5000:5000 stockdocs-scraper
docker build -t stockdocs-article-server ./articleServer
docker run -p 5008:5008 stockdocs-article-server
# Continue for other components...
```
## Key Technical Details
### Data Flow
1. **Scraper** collects articles from RSS feeds and stores them in `scraper/articles/`
2. **Article Server** provides API access to these articles
3. **AI Processor** analyzes articles and generates insights in `ai_processor/output/`
4. **Embedding Service** converts article content into vector representations and stores in ChromaDB
5. **MCPServer** provides API access to the vector database for querying
### Environment Variables
Each component may require specific environment variables:
- `ARTICLE_DIR`: Path to article directory
- `AI_SERVICE_URL`: URL for local AI service
- `CHROMADB_HOST` and `CHROMADB_PORT`: ChromaDB connection settings
- `FEED_FILE`: Path to RSS feed configuration file
### Directory Structure
- `scraper/articles/`: Stores raw scraped articles organized by news source
- `ai_processor/output/`: Stores processed AI analysis results
- `embedding/data/cache/`: Stores cached embeddings
- `MCPServer/`: Contains server configuration and API endpoints
## Getting Started Guide
To begin working with the StockDocs platform:
1. **Start the Scraper** to collect news articles
2. **Run the Article Server** to make articles accessible via API
3. **Launch the AI Processor** to analyze articles and generate insights
4. **Initialize the Embedding Service** to create vector representations
5. **Start MCPServer** to query the vector database for insights
Each component can be run independently or as part of a complete pipeline for comprehensive financial news analysis.

304
agent.md
View File

@ -1,304 +0,0 @@
# StockDocs Project Overview
This document provides a comprehensive overview of the StockDocs repository, which contains multiple interconnected projects for processing, scraping, and serving financial articles and embeddings.
## Repository Structure
The repository contains 5 main projects:
1. **ai_processor/** - AI processing component
2. **articleServer/** - Article serving component
3. **embedding/** - Embedding functionality
4. **MCPServer/** - MCP server component
5. **scraper/** - Web scraping component
## Project Details
### 1. ai_processor/
The AI processing component handles artificial intelligence operations for processing articles and generating insights.
**Key Files:**
- `ai_processor.py` - Main AI processing logic
- `requirements.txt` - Python dependencies
- `Dockerfile` - Container configuration
**Purpose:** Processes articles using AI models to extract key information, generate summaries, and create embeddings.
**Detailed Structure:**
```
ai_processor/
├── app.py # Main AI processing application
├── config.py # Configuration settings
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── README.md # This file
├── models/ # Machine learning models and NLP components
│ ├── __init__.py
│ ├── sentiment_analyzer.py # Sentiment analysis module
│ ├── topic_classifier.py # News categorization module
│ └── entity_extractor.py # Named entity recognition
├── processors/ # Article processing pipelines
│ ├── __init__.py
│ ├── text_processor.py # Text cleaning and preprocessing
│ └── analysis_pipeline.py # Full analysis pipeline
└── data/ # Processed data storage
├── insights/
└── reports/
```
**Endpoints:**
- POST `/api/analyze/article` - Analyze a single article for insights
- POST `/api/analyze/batch` - Process multiple articles in batch mode
- GET `/api/analyze/status/{task_id}` - Check processing status
- GET `/api/insights/latest` - Get latest analysis insights
- GET `/api/insights/articles/{article_path}` - Get insights for specific article
- GET `/api/reports/generate` - Generate comprehensive market analysis report
- GET `/api/models` - List available AI models
- POST `/api/models/update` - Update or retrain models with new data
### 2. articleServer/
The article serving component provides an API for accessing processed articles.
**Key Files:**
- `app.py` - Main Flask application
- `run_server.py` - Server startup script
- `requirements.txt` - Python dependencies
- `Dockerfile` - Container configuration
**Purpose:** Exposes processed articles through a REST API for client applications to consume.
**Detailed Structure:**
```
articleServer/
├── app.py # Main Flask application
├── run_server.py # Server startup script
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── README.md # This file
└── templates/ # HTML templates (if any)
```
**Endpoints:**
- GET `/articles` - Get articles within time range
- GET `/article/content` - Get full article content by path
- GET `/outlets` - List all available news outlets
- GET `/health` - Health check endpoint
### 3. embedding/
The embedding functionality handles vector embeddings for articles and documents.
**Key Files:**
- `embedder.py` - Embedding generation logic
- `requirements.txt` - Python dependencies
- `Dockerfile` - Container configuration
**Purpose:** Converts articles into vector embeddings for semantic search and similarity operations.
**Detailed Structure:**
```
embedding/
├── app.py # Main embedding application
├── config.py # Configuration settings
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── README.md # This file
├── models/ # Pre-trained embedding models
│ ├── __init__.py
│ ├── sentence_transformer.py # Sentence transformer implementation
│ └── model_loader.py # Model loading utilities
├── processors/ # Text processing pipeline
│ ├── __init__.py
│ ├── text_cleaner.py # Text cleaning and preprocessing
│ └── embedding_generator.py # Embedding generation
└── data/ # Processed embeddings storage
├── cache/
└── outputs/
```
**Endpoints:**
- POST `/api/embeddings/generate` - Generate embeddings for text content
- POST `/api/embeddings/batch` - Generate embeddings for multiple texts in batch
- GET `/api/embeddings/similarity` - Calculate similarity between two pieces of text/content
- GET `/api/embeddings/status` - Check service status
- GET `/api/embeddings/models` - List available embedding models
- DELETE `/api/embeddings/cache/clear` - Clear the embedding cache
### 4. MCPServer/
The MCP (Model Context Protocol) server component provides external API access.
**Key Files:**
- `server.py` - Main MCP server implementation
- `openapi.json` - API specification
- `requirements.txt` - Python dependencies
- `Dockerfile` - Container configuration
**Purpose:** Exposes functionality through the Model Context Protocol for integration with other systems.
**Detailed Structure:**
```
MCPServer/
├── server.py # Main Flask application
├── config.py # Configuration settings
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
├── README.md # This file
└── api/ # API endpoints and handlers
├── __init__.py
├── stock_analysis.py # Stock analysis functions
└── news_processing.py # News processing functions
```
**Endpoints:**
- GET `/api/stock/metrics` - Get financial metrics for a stock
- GET `/api/stock/history` - Get historical price data
- POST `/api/stock/analyze` - Perform comprehensive stock analysis
- GET `/api/news` - Retrieve news articles related to stocks
- GET `/api/news/outlets` - List available news sources
- POST `/api/news/process` - Process and categorize news content
- GET `/api/data/refresh` - Refresh data from sources
- GET `/api/status` - Server health check
### 5. scraper/
The web scraping component collects articles from various sources.
**Key Files:**
- `scraper.py` - Main scraping logic
- `rss_feeds.json` - RSS feed configuration
- `requirements.txt` - Python dependencies
- `Dockerfile` - Container configuration
**Purpose:** Collects financial articles from various sources including RSS feeds and web scraping.
**Detailed Structure:**
```
scraper/
├── rss_feeds.json # Configuration file with RSS feed URLs
├── scraper.py # Main scraping logic
├── requirements.txt # Python dependencies
├── dockerfile # Docker configuration
├── dockerfile-selenium # Dockerfile for selenium-based scraping
├── articles/ # Directory where scraped articles are stored
│ ├── Reuters Business News/
│ │ ├── article1.txt
│ │ └── ...
│ ├── Associated Press Business/
│ │ ├── article1.txt
│ │ └── ...
│ └── ...
├── processed_articles_cache.json # Cache of already processed articles
└── pyvenv.cfg # Python virtual environment configuration
```
**Features:**
- RSS Feed Integration: Supports multiple financial news sources through RSS feeds
- Automated Scraping: Regularly fetches and processes new articles from configured feeds
- Structured Storage: Organizes articles in a directory structure by news outlet
- Duplicate Detection: Prevents re-processing of already collected articles
- Caching Mechanism: Maintains a cache of processed articles to optimize performance
## Getting Started
### Prerequisites
- Docker installed
- Python 3.8+
- Git
### Setup Instructions
1. **Clone the repository:**
```bash
git clone <repository-url>
cd StockDocs
```
2. **Build and run containers:**
```bash
docker-compose up --build
```
3. **Project-specific setup:**
- Each project has its own `README.md` with detailed setup instructions
- Check individual project directories for specific requirements
## Project Dependencies
### Common Dependencies
- Python 3.8+
- Docker
- Various Python packages (listed in requirements.txt files)
### Inter-project Relationships
- `scraper/` feeds articles to `ai_processor/`
- `ai_processor/` generates embeddings that `embedding/` processes
- `articleServer/` serves articles processed by `ai_processor/`
- `MCPServer/` provides API access to all components
## Development Workflow
1. **Start all services:**
```bash
docker-compose up --build
```
2. **Work with individual projects:**
- Navigate to project directory
- Check `README.md` for specific instructions
- Make changes and rebuild as needed
3. **Testing:**
- Each project includes its own testing setup
- Integration tests may be needed for cross-project functionality
## API Endpoints
### articleServer/
- `/articles` - Get all articles
- `/articles/<id>` - Get specific article
- `/search` - Search articles by query
### MCPServer/
- Exposes various endpoints through Model Context Protocol
- See `openapi.json` for complete specification
## Configuration
### Environment Variables
Each project may require specific environment variables. Check individual `README.md` files for details.
### Authentication
The system now supports API key authentication for connections to the centralized AI service at `http://example.com:4000`. To enable authentication:
1. Set the `AI_SERVICE_API_KEY` environment variable with your API key
2. All connections to the AI service will automatically include the `Authorization: Bearer {api_key}` header
### Data Storage
- Articles are stored in the scraper component
- Processed data flows through the ai_processor
- Embeddings are generated and stored in the embedding component
## Troubleshooting
### Common Issues
1. **Docker build failures:** Ensure Docker is running and check `Dockerfile` syntax
2. **Python dependency issues:** Run `pip install -r requirements.txt` in each project
3. **Port conflicts:** Check `docker-compose.yml` for port mappings
4. **Service startup issues:** Check individual project logs
### Logs
- View logs with `docker-compose logs <service-name>`
- Check individual project logs for detailed error information
## Contributing
1. Fork the repository
2. Create feature branch
3. Make changes
4. Test thoroughly
5. Submit pull request
## Support
For issues or questions, please check:
- Individual project README.md files
- Docker logs for runtime errors
- GitHub issues for known problems

View File

@ -60,7 +60,7 @@ class ArticleProcessor:
scraper_dir = alt_path
break
else:
logger.error(f"No valid articles directory found")
logger.error("No valid articles directory found")
return []
# Log cache state before scanning
@ -69,7 +69,7 @@ class ArticleProcessor:
f"Cache state before scanning: {cache_stats['processed_files']} files marked as processed"
)
logger.info(f"Directory exists, walking through files...")
logger.info("Directory exists, walking through files...")
file_count = 0
article_file_count = 0
already_processed_count = 0

View File

@ -6,7 +6,7 @@ import json
import logging
import os
from datetime import datetime
from typing import Dict, List, Optional
from typing import Dict, List
from config import CACHE_FILE

View File

@ -6,7 +6,7 @@ Uses the gpt-oss model via the centralized AI service.
import json
import logging
import requests
from typing import Dict, Any, Optional
from typing import Dict, Any
from config import AI_SERVER_URL, AI_SERVICE_API_KEY, FACT_EXTRACTION_MODEL
from metrics_collector import metrics_collector

View File

@ -6,11 +6,9 @@ Handles the orchestration of article processing and fact extraction.
import logging
import sys
import os
from datetime import datetime
from article_processor import ArticleProcessor
from metrics_collector import metrics_collector
from cache_manager import CacheManager
from config import CACHE_FILE, LOG_FILE, LOG_LEVEL
# Setup logging

View File

@ -1,5 +0,0 @@
home = /usr/bin
include-system-site-packages = false
version = 3.12.3
executable = /usr/bin/python3.12
command = /usr/bin/python3 -m venv /home/user/StockDocs/articleServer

View File

@ -2,11 +2,9 @@ import os
import json
import chromadb
import uuid
import time
import datetime
import requests
import logging
from pathlib import Path
from prometheus_client import start_http_server, Counter, Histogram
# Setup logging with better error handling
@ -19,7 +17,7 @@ try:
logging.StreamHandler()
]
)
except Exception as e:
except Exception:
# Fallback if file logging fails
logging.basicConfig(
level=logging.INFO,

View File

@ -1,3 +1,4 @@
import math
import os
import json
import chromadb
@ -15,8 +16,6 @@ model = SentenceTransformer(
trust_remote_code=True
)
import math
def embed_text(text, specific_context, max_tokens=2048, overlap=256):
"""
Embeds the given text using the SentenceTransformer model.

View File

@ -100,7 +100,7 @@ def check_scraper_directory():
health_status.labels(component='scraper_dir').set(1)
return True
else:
logger.warning(f"⚠ Scraper directory exists but no JSON files found")
logger.warning("⚠ Scraper directory exists but no JSON files found")
health_status.labels(component='scraper_dir').set(1) # Directory exists, just no files yet
return True

View File

@ -6,8 +6,6 @@ This shows how to connect and query your ChromaDB database
import os
import chromadb
import json
from pathlib import Path
from chromadb.config import Settings
def connect_to_chromadb():

View File

@ -5,8 +5,6 @@ Test script to demonstrate end-to-end pipeline with a single article
import os
import json
import tempfile
from pathlib import Path
# Add the current directory to Python path to import our modules
import sys
@ -14,10 +12,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from advanced_embedder import (
extract_facts_from_article,
get_embedding,
create_collections,
embed_and_store_facts,
process_article_file
get_embedding
)
def test_end_to_end():

48
pyproject.toml Normal file
View File

@ -0,0 +1,48 @@
[project]
name = "stockdocs"
version = "1.0.0"
description = "Financial news analysis platform: RSS scraping, AI processing, embeddings, and MCP server"
readme = "README.md"
requires-python = ">=3.9"
license = { text = "MIT" }
authors = [{ name = "Jarian Cottingham", email = "jarianc@proton.me" }]
keywords = ["finance", "news", "scraping", "nlp", "embeddings", "mcp"]
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
]
dependencies = [
"feedparser>=6.0,<7.0",
"requests>=2.31,<3.0",
"beautifulsoup4>=4.12,<5.0",
"lxml>=5.0",
"nltk>=3.8",
"newspaper4k>=0.2.8,<0.3",
"selenium>=4.15",
"pandas>=2.0",
"pyyaml>=6.0",
"tqdm>=4.64",
"tldextract>=5.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"ruff>=0.1.0",
]
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[tool.ruff]
line-length = 120
target-version = "py39"
exclude = [".git", "articles", "ai_processor/ai_processor"]
[tool.ruff.lint]
select = ["E", "F", "W"]
ignore = ["E501"]
[tool.pytest.ini_options]
testpaths = ["tests"]

BIN
scraper/.DS_Store vendored

Binary file not shown.

View File

@ -6,7 +6,6 @@ that can be scheduled via cron job.
"""
import newspaper
from newspaper import Config
import json
import feedparser
import time
@ -14,7 +13,6 @@ import os
import requests
import logging
import random
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.common.by import By
@ -50,7 +48,6 @@ def get_feed_file_path():
possible_paths = [
"./rss_feeds.json", # Current directory
"../rss_feeds.json", # Parent directory
"/home/user/StockDocs/scraper/rss_feeds.json", # Explicit path
"/app/rss_feeds.json", # Docker path
"./scraper/rss_feeds.json" # Scraper subdirectory
]
@ -204,7 +201,7 @@ def get_article_with_selenium(url):
WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
except:
except Exception:
pass
time.sleep(random.uniform(1, 3))
@ -224,7 +221,7 @@ def get_article_with_selenium(url):
if driver:
try:
driver.quit()
except:
except Exception:
pass
@ -293,7 +290,6 @@ def pull_article(link, source, title=None, save_to_file=True):
try:
# Try newspaper4k first with proper User-Agent to bypass bot detection
ua = get_random_ua()
config = Config(browser_user_agent=ua)
article = newspaper.article(link, browser_user_agent=ua)
article.download()
article.parse()
@ -315,7 +311,7 @@ def pull_article(link, source, title=None, save_to_file=True):
logger.info(f"Successfully pulled article from {link} with Playwright")
if not text or len(text) < 200:
logger.warning(f"Playwright article too short, falling back to Selenium.")
logger.warning("Playwright article too short, falling back to Selenium.")
# Fallback to Selenium with better error handling
text = get_article_with_selenium(link)
logger.info(f"Successfully pulled article from {link} with Selenium")
@ -464,7 +460,7 @@ def main():
with open("errors.txt", "w", encoding="utf-8") as f:
for error in errors:
f.write(str(error) + "\n")
logger.info(f"Errors logged to errors.txt")
logger.info("Errors logged to errors.txt")
# Print all results to a log file
with open("results.txt", "w", encoding="utf-8") as f:

View File

@ -1,5 +0,0 @@
home = /usr/bin
include-system-site-packages = false
version = 3.12.3
executable = /usr/bin/python3.12
command = /usr/bin/python3 -m venv /home/user/StockDocs/scraper

View File

@ -1,5 +1,4 @@
import newspaper
from newspaper import Config
import json
import feedparser
import time
@ -286,7 +285,7 @@ def get_article_with_selenium(url):
WebDriverWait(driver, 15).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
except:
except Exception:
pass # Continue even if wait times out
time.sleep(random.uniform(1, 3)) # Random wait to mimic human behavior
@ -313,7 +312,7 @@ def get_article_with_selenium(url):
if driver:
try:
driver.quit()
except:
except Exception:
pass # Ignore errors in cleanup
@ -387,7 +386,6 @@ def pull_article(link, source, title=None, save_to_file=True):
try:
# Try newspaper4k first with proper User-Agent to bypass bot detection
ua = get_random_ua()
config = Config(browser_user_agent=ua)
article = newspaper.article(link, browser_user_agent=ua)
article.download()
article.parse()
@ -409,7 +407,7 @@ def pull_article(link, source, title=None, save_to_file=True):
logger.info(f"Successfully pulled article from {link} with Playwright")
if not text or len(text) < 200:
logger.warning(f"Playwright article too short, falling back to Selenium.")
logger.warning("Playwright article too short, falling back to Selenium.")
# Fallback to Selenium with better error handling
text = get_article_with_selenium(link)
logger.info(f"Successfully pulled article from {link} with Selenium")
@ -542,7 +540,7 @@ def main():
with open("errors.txt", "w", encoding="utf-8") as f:
for error in errors:
f.write(str(error) + "\n")
logger.info(f"Errors logged to errors.txt")
logger.info("Errors logged to errors.txt")
# Print all results to a log file
with open("results.txt", "w", encoding="utf-8") as f:

View File

@ -1,43 +0,0 @@
#!/usr/bin/env python3
"""
Test script to verify the enhanced cache system implementation
"""
import json
import os
import datetime
from scraper.scraper import load_processed_cache, save_processed_cache, get_processing_progress
def test_cache_system():
"""Test the enhanced cache system"""
print("Testing enhanced cache system...")
# Test loading cache (should work even if file doesn't exist)
cache = load_processed_cache()
print(f"Initial cache loaded: {len(cache)} entries")
# Test saving cache
test_entry = {
"test_article_path": {
"processed_date": datetime.datetime.now().isoformat(),
"status": "completed",
"embedding_status": "pending",
"last_updated": datetime.datetime.now().isoformat()
}
}
save_processed_cache(test_entry)
print("Cache saved successfully")
# Test loading again
cache = load_processed_cache()
print(f"Cache loaded after save: {len(cache)} entries")
# Test progress tracking
progress = get_processing_progress()
print(f"Progress tracking: {progress}")
print("Cache system test completed successfully!")
if __name__ == "__main__":
test_cache_system()

View File

@ -0,0 +1,61 @@
"""Tests for the scraper article-processing cache."""
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from scraper.scraper import ( # noqa: E402
get_processing_progress,
load_processed_cache,
mark_article_processed,
save_processed_cache,
)
@pytest.fixture()
def cache_dir(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
(tmp_path / "articles").mkdir()
return tmp_path
def test_load_missing_cache_returns_empty(cache_dir):
assert load_processed_cache() == {}
def test_save_and_load_roundtrip(cache_dir):
save_processed_cache({"a.html": {"status": "completed"}})
cache = load_processed_cache()
assert cache["a.html"]["status"] == "completed"
def test_mark_article_processed(cache_dir):
mark_article_processed("articles/x/article.html")
cache = load_processed_cache()
entry = cache["articles/x/article.html"]
assert entry["status"] == "completed"
assert entry["embedding_status"] == "pending"
assert "processed_date" in entry
assert "last_updated" in entry
def test_processing_progress_empty(cache_dir):
progress = get_processing_progress()
assert progress["total_articles"] == 0
assert progress["completed_articles"] == 0
assert progress["embedded_articles"] == 0
assert progress["completion_rate"] == 0
def test_processing_progress_mixed(cache_dir):
mark_article_processed("a.html")
mark_article_processed("b.html", status="failed")
mark_article_processed("c.html", embedding_status="completed")
progress = get_processing_progress()
assert progress["total_articles"] == 3
assert progress["completed_articles"] == 2
assert progress["embedded_articles"] == 1
assert progress["completion_rate"] == pytest.approx(2 / 3 * 100)