about summary refs log tree commit diff stats
path: root/js/sentiment
diff options
context:
space:
mode:
authorelioat <elioat@tilde.institute>2025-02-23 20:52:43 -0500
committerelioat <elioat@tilde.institute>2025-02-23 20:52:43 -0500
commit883bd856bc05ea72239e89ca262941c75c70fefd (patch)
tree3a41e83f9af8460add01a509975c3d45ac118a87 /js/sentiment
parent81d27f6b6984ba41f40824ca2dc6d1962f9176a3 (diff)
downloadtour-883bd856bc05ea72239e89ca262941c75c70fefd.tar.gz
*
Diffstat (limited to 'js/sentiment')
-rw-r--r--js/sentiment/.gitignore175
-rw-r--r--js/sentiment/README.md108
-rw-r--r--js/sentiment/app.js757
-rwxr-xr-xjs/sentiment/bun.lockbbin0 -> 25383 bytes
-rw-r--r--js/sentiment/jsconfig.json27
-rw-r--r--js/sentiment/package.json14
6 files changed, 1081 insertions, 0 deletions
diff --git a/js/sentiment/.gitignore b/js/sentiment/.gitignore
new file mode 100644
index 0000000..9b1ee42
--- /dev/null
+++ b/js/sentiment/.gitignore
@@ -0,0 +1,175 @@
+# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
+
+# Logs
+
+logs
+_.log
+npm-debug.log_
+yarn-debug.log*
+yarn-error.log*
+lerna-debug.log*
+.pnpm-debug.log*
+
+# Caches
+
+.cache
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+
+report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
+
+# Runtime data
+
+pids
+_.pid
+_.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+
+lib-cov
+
+# Coverage directory used by tools like istanbul
+
+coverage
+*.lcov
+
+# nyc test coverage
+
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+
+bower_components
+
+# node-waf configuration
+
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+
+build/Release
+
+# Dependency directories
+
+node_modules/
+jspm_packages/
+
+# Snowpack dependency directory (https://snowpack.dev/)
+
+web_modules/
+
+# TypeScript cache
+
+*.tsbuildinfo
+
+# Optional npm cache directory
+
+.npm
+
+# Optional eslint cache
+
+.eslintcache
+
+# Optional stylelint cache
+
+.stylelintcache
+
+# Microbundle cache
+
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+
+.node_repl_history
+
+# Output of 'npm pack'
+
+*.tgz
+
+# Yarn Integrity file
+
+.yarn-integrity
+
+# dotenv environment variable files
+
+.env
+.env.development.local
+.env.test.local
+.env.production.local
+.env.local
+
+# parcel-bundler cache (https://parceljs.org/)
+
+.parcel-cache
+
+# Next.js build output
+
+.next
+out
+
+# Nuxt.js build / generate output
+
+.nuxt
+dist
+
+# Gatsby files
+
+# Comment in the public line in if your project uses Gatsby and not Next.js
+
+# https://nextjs.org/blog/next-9-1#public-directory-support
+
+# public
+
+# vuepress build output
+
+.vuepress/dist
+
+# vuepress v2.x temp and cache directory
+
+.temp
+
+# Docusaurus cache and generated files
+
+.docusaurus
+
+# Serverless directories
+
+.serverless/
+
+# FuseBox cache
+
+.fusebox/
+
+# DynamoDB Local files
+
+.dynamodb/
+
+# TernJS port file
+
+.tern-port
+
+# Stores VSCode versions used for testing VSCode extensions
+
+.vscode-test
+
+# yarn v2
+
+.yarn/cache
+.yarn/unplugged
+.yarn/build-state.yml
+.yarn/install-state.gz
+.pnp.*
+
+# IntelliJ based IDEs
+.idea
+
+# Finder (MacOS) folder config
+.DS_Store
diff --git a/js/sentiment/README.md b/js/sentiment/README.md
new file mode 100644
index 0000000..141470d
--- /dev/null
+++ b/js/sentiment/README.md
@@ -0,0 +1,108 @@
+# Sentiment Analyzer
+
+## Overview
+
+The Sentiment Analyzer is a JavaScript application designed to analyze the sentiment of web content. It utilizes a combination of dictionary-based sentiment analysis, emotion categorization, intensity analysis, web content extraction, and metadata parsing to provide a comprehensive emotional analysis of text from web pages.
+
+### Key Features
+
+- **Emotion Categorization**: Classifies emotions into various categories such as joy, sadness, anger, and more.
+- **Intensity Analysis**: Measures the intensity of sentiments based on the context and usage of words.
+- **Web Content Extraction**: Fetches and extracts meaningful content from web pages, ignoring irrelevant sections like headers and footers.
+- **Metadata Parsing**: Extracts useful metadata such as titles, authors, and publication dates from web pages.
+
+## Installation
+
+To install dependencies, run:
+
+```bash
+bun install
+```
+
+## Usage
+
+To run the sentiment analyzer, use the following command:
+
+```bash
+bun run app.js <url>
+```
+
+You can also analyze multiple URLs at once:
+
+```bash
+bun run app.js <url1> <url2> <url3>
+```
+
+### Example
+
+```bash
+bun run app.js https://example.com/blog-post
+```
+
+### Help
+
+To display help information, use:
+
+```bash
+bun run app.js --help
+```
+
+## Building a Static Binary
+
+Bun allows you to build your application as a static binary, which can be distributed and run without requiring a separate runtime environment. To build the Sentiment Analyzer as a binary, follow these steps:
+
+1. **Build the Binary**: Run the following command in your terminal:
+
+   ```bash
+   bun build app.js --outdir ./bin --target node
+   ```
+
+   This command compiles your application into a single binary executable for Node.js and places it in the `./bin` directory.
+
+2. **Run the Binary**: After building, you can run the binary directly:
+
+   ```bash
+   ./bin/app.js <url>
+   ```
+
+   Or for multiple URLs:
+
+   ```bash
+   ./bin/app.js <url1> <url2> <url3>
+   ```
+
+### Example
+
+```bash
+./bin/app.js https://example.com/blog-post
+```
+
+## Extending the Program
+
+The Sentiment Analyzer is designed to be extensible. Here are some ways you can enhance its functionality:
+
+1. **Add More Dictionaries**: You can extend the positive and negative word dictionaries by adding more words or phrases relevant to specific contexts or industries.
+
+2. **Enhance Emotion Categories**: Modify the `emotionCategories` object in `app.js` to include additional emotions or synonyms that are relevant to your analysis needs.
+
+3. **Implement Machine Learning**: Consider integrating machine learning models for more advanced sentiment analysis that can learn from context and improve over time.
+
+4. **Support for Multiple Languages**: Extend the program to support sentiment analysis in different languages by adding language-specific dictionaries and rules.
+
+5. **Dynamic Content Handling**: Improve the content extraction logic to handle dynamic web pages (Single Page Applications) that load content asynchronously.
+
+6. **Batch Processing**: Implement functionality to read URLs from a file and process them in batches, which can be useful for analyzing large datasets.
+
+7. **Output Formatting Options**: Add options to format the output in different ways (e.g., JSON, CSV) for easier integration with other tools or systems.
+
+## Contributing
+
+Contributions are welcome! If you have suggestions for improvements or new features, feel free to open an issue or submit a pull request.
+
+## License
+
+This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
+
+## Acknowledgments
+
+This project was created using `bun init` in bun v1.1.29. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
diff --git a/js/sentiment/app.js b/js/sentiment/app.js
new file mode 100644
index 0000000..66735fd
--- /dev/null
+++ b/js/sentiment/app.js
@@ -0,0 +1,757 @@
+/**
+ * Web Sentiment Analyzer
+ * 
+ * This program analyzes the sentiment of web content using a combination of:
+ * - Dictionary-based sentiment analysis
+ * - Emotion categorization
+ * - Intensity analysis
+ * - Web content extraction
+ * - Metadata parsing
+ * 
+ * Architecture Overview:
+ * - Factory Pattern: Uses createWebSentimentAnalyzer to create analyzer instances
+ * - Builder Pattern: Configurable through dictionary additions and modifications
+ * - Strategy Pattern: Separates content fetching, analysis, and display logic
+ * - Command Pattern: CLI interface for processing multiple URLs
+ * 
+ * @module sentiment-analyzer
+ */
+
+import { JSDOM } from 'jsdom';
+
+/**
+ * Creates a web-enabled sentiment analyzer with extended capabilities
+ * 
+ * @param {Object} config - Optional configuration to override default dictionaries
+ * @returns {Object} An analyzer instance with public methods for sentiment analysis
+ * 
+ * Extensibility Points:
+ * - Add more dictionaries (e.g., industry-specific terms)
+ * - Enhance emotion categories
+ * - Add language support
+ * - Implement ML-based sentiment analysis
+ */
+const createWebSentimentAnalyzer = (config = {}) => {
+    /**
+     * Default configuration with extensive sentiment dictionaries
+     * 
+     * @property {Set} positiveWords - Words indicating positive sentiment
+     * @property {Set} negativeWords - Words indicating negative sentiment
+     * @property {Map} intensifiers - Words that modify sentiment intensity
+     * @property {Set} negators - Words that negate sentiment
+     * 
+     * Potential Enhancements:
+     * - Add multi-word phrases
+     * - Include context-dependent sentiments
+     * - Add domain-specific dictionaries
+     */
+    const defaultConfig = {
+      positiveWords: new Set([
+        // Emotional positives
+        'love', 'joy', 'happy', 'excited', 'peaceful', 'wonderful', 'fantastic',
+        'delighted', 'pleased', 'glad', 'cheerful', 'content', 'satisfied',
+        'grateful', 'thankful', 'blessed', 'optimistic', 'hopeful',
+        
+        // Quality positives
+        'excellent', 'outstanding', 'superb', 'magnificent', 'brilliant',
+        'exceptional', 'perfect', 'remarkable', 'spectacular', 'impressive',
+        'incredible', 'amazing', 'extraordinary', 'marvelous', 'wonderful',
+        
+        // Performance positives
+        'efficient', 'effective', 'reliable', 'innovative', 'productive',
+        'successful', 'accomplished', 'achieved', 'improved', 'enhanced',
+        'optimized', 'streamlined', 'breakthrough', 'revolutionary',
+        
+        // Relationship positives
+        'friendly', 'helpful', 'supportive', 'kind', 'generous', 'caring',
+        'compassionate', 'thoughtful', 'considerate', 'engaging', 'collaborative',
+        
+        // Experience positives
+        'enjoyable', 'fun', 'entertaining', 'engaging', 'interesting', 'fascinating',
+        'captivating', 'inspiring', 'motivating', 'enriching', 'rewarding',
+        
+        // Growth positives
+        'growing', 'improving', 'developing', 'advancing', 'progressing',
+        'evolving', 'flourishing', 'thriving', 'prospering', 'succeeding'
+      ]),
+      
+      negativeWords: new Set([
+        // Emotional negatives
+        'hate', 'angry', 'sad', 'upset', 'frustrated', 'disappointed', 'anxious',
+        'worried', 'stressed', 'depressed', 'miserable', 'unhappy', 'distressed',
+        'irritated', 'annoyed', 'furious', 'outraged', 'bitter',
+        
+        // Quality negatives
+        'poor', 'bad', 'terrible', 'horrible', 'awful', 'dreadful', 'inferior',
+        'mediocre', 'subpar', 'unacceptable', 'disappointing', 'inadequate',
+        'deficient', 'flawed', 'defective',
+        
+        // Performance negatives
+        'inefficient', 'ineffective', 'unreliable', 'problematic', 'failing',
+        'broken', 'malfunctioning', 'corrupted', 'crashed', 'buggy', 'error',
+        'failed', 'unsuccessful', 'unproductive',
+        
+        // Relationship negatives
+        'hostile', 'unfriendly', 'unhelpful', 'rude', 'mean', 'cruel', 'harsh',
+        'inconsiderate', 'selfish', 'aggressive', 'confrontational', 'toxic',
+        
+        // Experience negatives
+        'boring', 'dull', 'tedious', 'monotonous', 'uninteresting', 'tiresome',
+        'exhausting', 'frustrating', 'confusing', 'complicated', 'difficult',
+        
+        // Decline negatives
+        'declining', 'deteriorating', 'worsening', 'failing', 'regressing',
+        'degrading', 'diminishing', 'decreasing', 'falling', 'shrinking'
+      ]),
+      
+      intensifiers: new Map([
+        // Strong intensifiers
+        ['extremely', 2.0],
+        ['absolutely', 2.0],
+        ['completely', 2.0],
+        ['totally', 2.0],
+        ['entirely', 2.0],
+        ['utterly', 2.0],
+        
+        // Moderate intensifiers
+        ['very', 1.5],
+        ['really', 1.5],
+        ['particularly', 1.5],
+        ['especially', 1.5],
+        ['notably', 1.5],
+        ['significantly', 1.5],
+        
+        // Mild intensifiers
+        ['quite', 1.25],
+        ['rather', 1.25],
+        ['somewhat', 1.25],
+        ['fairly', 1.25],
+        ['pretty', 1.25],
+        ['relatively', 1.25],
+        
+        // Emphatic phrases
+        ['without a doubt', 2.0],
+        ['beyond question', 2.0],
+        ['by far', 1.75],
+        ['to a great extent', 1.75]
+      ]),
+      
+      negators: new Set([
+        // Direct negators
+        'not', 'no', 'never', 'none', 'neither', 'nor', 'nothing',
+        
+        // Contracted negators
+        "n't", 'cannot', "won't", "wouldn't", "shouldn't", "couldn't", "haven't",
+        "hasn't", "didn't", "isn't", "aren't", "weren't",
+        
+        // Complex negators
+        'hardly', 'scarcely', 'barely', 'rarely', 'seldom', 'few', 'little',
+        'nowhere', 'nobody', 'none', 'by no means', 'on no account',
+        
+        // Implicit negators
+        'deny', 'reject', 'refuse', 'prevent', 'avoid', 'stop', 'exclude',
+        'doubt', 'question', 'dispute'
+      ])
+    };
+  
+    // Merge with provided config
+    const finalConfig = { ...defaultConfig, ...config };
+  
+    /**
+     * Core sentiment analyzer implementation
+     * 
+     * @param {Object} config - Configuration object with word dictionaries
+     * @returns {Object} Methods for text analysis
+     * 
+     * Implementation Notes:
+     * - Uses a sliding window approach for context analysis
+     * - Implements multiplier-based intensity scoring
+     * - Categorizes emotions using predefined taxonomies
+     */
+    const createSentimentAnalyzer = (config) => {
+        /**
+         * Main text analysis function
+         * 
+         * @param {string} text - Text to analyze
+         * @returns {Object} Comprehensive analysis results
+         * 
+         * Potential Improvements:
+         * - Add sentence-level analysis
+         * - Implement paragraph breakdown
+         * - Add statistical confidence scores
+         * - Consider word positioning and emphasis
+         */
+        const analyzeText = (text) => {
+            // Ensure text is a string and has content
+            if (!text || typeof text !== 'string') {
+                console.warn('Invalid input to analyzeText:', text);
+                return {
+                    score: 0,
+                    words: [],
+                    summary: { positive: 0, negative: 0, neutral: 0 },
+                    sentiment: 'Neutral',
+                    topEmotions: [],
+                    intensity: 'None',
+                    wordCount: 0
+                };
+            }
+            
+            const words = text.toLowerCase()
+                .replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '')
+                .split(/\s+/);
+                
+            let score = 0;
+            let multiplier = 1;
+            const analyzedWords = [];
+            const emotionCounts = new Map();
+            let positiveCount = 0;
+            let negativeCount = 0;
+            let intensifierCount = 0;
+            
+            // Emotion categories for classification
+            const emotionCategories = {
+                // Positive Emotions
+                joy: ['happy', 'joy', 'delighted', 'pleased', 'excited', 'ecstatic', 'elated', 'jubilant', 'thrilled', 'overjoyed'],
+                gratitude: ['grateful', 'thankful', 'blessed', 'appreciative', 'indebted', 'humbled', 'moved'],
+                satisfaction: ['content', 'satisfied', 'fulfilled', 'pleased', 'accomplished', 'proud', 'complete'],
+                optimism: ['optimistic', 'hopeful', 'promising', 'confident', 'assured', 'encouraged', 'positive'],
+                serenity: ['peaceful', 'calm', 'tranquil', 'relaxed', 'serene', 'composed', 'centered'],
+                amusement: ['fun', 'funny', 'amused', 'entertained', 'playful', 'silly', 'humorous', 'laughing'],
+                interest: ['curious', 'intrigued', 'fascinated', 'engaged', 'absorbed', 'captivated', 'inspired'],
+                admiration: ['impressed', 'awed', 'amazed', 'respected', 'valued', 'esteemed', 'revered'],
+                love: ['loving', 'adoring', 'fond', 'affectionate', 'caring', 'cherished', 'devoted'],
+                
+                // Negative Emotions
+                frustration: ['frustrated', 'annoyed', 'irritated', 'agitated', 'exasperated', 'thwarted', 'hindered'],
+                concern: ['worried', 'concerned', 'anxious', 'uneasy', 'apprehensive', 'troubled', 'disturbed'],
+                disappointment: ['disappointed', 'letdown', 'dissatisfied', 'disheartened', 'dismayed', 'unfulfilled'],
+                anger: ['angry', 'furious', 'outraged', 'enraged', 'hostile', 'irate', 'livid', 'incensed'],
+                sadness: ['sad', 'unhappy', 'sorrowful', 'depressed', 'melancholy', 'gloomy', 'heartbroken'],
+                fear: ['afraid', 'scared', 'fearful', 'terrified', 'panicked', 'petrified', 'dreading'],
+                confusion: ['confused', 'puzzled', 'perplexed', 'bewildered', 'disoriented', 'uncertain', 'unclear'],
+                regret: ['regretful', 'sorry', 'remorseful', 'guilty', 'apologetic', 'ashamed', 'contrite'],
+                
+                // Complex Emotions
+                anticipation: ['eager', 'anticipating', 'expecting', 'awaiting', 'looking forward', 'preparing'],
+                surprise: ['surprised', 'astonished', 'startled', 'shocked', 'stunned', 'unexpected', 'remarkable'],
+                nostalgia: ['nostalgic', 'reminiscent', 'remembering', 'longing', 'wistful', 'retrospective'],
+                determination: ['determined', 'resolved', 'committed', 'focused', 'dedicated', 'persistent', 'steadfast'],
+                relief: ['relieved', 'reassured', 'unburdened', 'comforted', 'calmed', 'settled', 'eased'],
+                ambivalence: ['conflicted', 'uncertain', 'unsure', 'mixed feelings', 'undecided', 'torn'],
+                
+                // Professional/Work-Related
+                confidence: ['confident', 'capable', 'competent', 'skilled', 'proficient', 'qualified', 'expert'],
+                motivation: ['motivated', 'driven', 'inspired', 'energized', 'enthusiastic', 'passionate', 'eager'],
+                productivity: ['productive', 'efficient', 'effective', 'accomplished', 'successful', 'achieving'],
+                collaboration: ['collaborative', 'cooperative', 'supportive', 'helpful', 'team-oriented', 'united'],
+                
+                // Growth/Learning
+                growth: ['growing', 'developing', 'improving', 'progressing', 'advancing', 'learning', 'evolving'],
+                curiosity: ['curious', 'inquisitive', 'interested', 'exploring', 'discovering', 'wondering'],
+                insight: ['understanding', 'realizing', 'comprehending', 'grasping', 'enlightened', 'aware']
+            };
+            
+            for (let i = 0; i < words.length; i++) {
+                const word = words[i];
+                let wordImpact = {
+                    word,
+                    score: 0,
+                    multiplier,
+                    category: null
+                };
+                
+                // Check for intensifiers
+                if (config.intensifiers.has(word)) {
+                    multiplier = config.intensifiers.get(word);
+                    intensifierCount++;
+                    continue;
+                }
+                
+                // Check for negators
+                if (config.negators.has(word)) {
+                    multiplier *= -1;
+                    continue;
+                }
+                
+                // Score the word and categorize emotions
+                if (config.positiveWords.has(word)) {
+                    const wordScore = 1 * multiplier;
+                    score += wordScore;
+                    positiveCount++;
+                    wordImpact.score = wordScore;
+                    
+                    // Categorize emotion
+                    for (const [category, keywords] of Object.entries(emotionCategories)) {
+                        if (keywords.includes(word)) {
+                            wordImpact.category = category;
+                            emotionCounts.set(category, (emotionCounts.get(category) || 0) + 1);
+                            break;
+                        }
+                    }
+                    
+                } else if (config.negativeWords.has(word)) {
+                    const wordScore = -1 * multiplier;
+                    score += wordScore;
+                    negativeCount++;
+                    wordImpact.score = wordScore;
+                    
+                    // Categorize emotion
+                    for (const [category, keywords] of Object.entries(emotionCategories)) {
+                        if (keywords.includes(word)) {
+                            wordImpact.category = category;
+                            emotionCounts.set(category, (emotionCounts.get(category) || 0) + 1);
+                            break;
+                        }
+                    }
+                }
+                
+                if (wordImpact.score !== 0 || wordImpact.category) {
+                    analyzedWords.push(wordImpact);
+                }
+                
+                // Reset multiplier after scoring a word
+                multiplier = 1;
+            }
+            
+            // Calculate intensity based on score magnitude and intensifier usage
+            const getIntensity = (score, intensifierCount) => {
+                const magnitude = Math.abs(score);
+                if (magnitude > 10 || intensifierCount > 5) return 'Very Strong';
+                if (magnitude > 7 || intensifierCount > 3) return 'Strong';
+                if (magnitude > 4 || intensifierCount > 1) return 'Moderate';
+                if (magnitude > 0) return 'Mild';
+                return 'Neutral';
+            };
+            
+            // Get top emotions
+            const topEmotions = Array.from(emotionCounts.entries())
+                .sort((a, b) => b[1] - a[1])
+                .slice(0, 3)
+                .map(([emotion, count]) => ({ emotion, count }));
+            
+            return {
+                score,
+                words: analyzedWords,
+                summary: {
+                    positive: positiveCount,
+                    negative: negativeCount,
+                    neutral: words.length - positiveCount - negativeCount,
+                    total: words.length
+                },
+                sentiment: getEmotionalTone(score),
+                topEmotions,
+                intensity: getIntensity(score, intensifierCount),
+                wordCount: words.length,
+                averageSentiment: score / words.length || 0
+            };
+        };
+
+        return {
+            analyzeText,
+            calculateSentimentScore: (text) => analyzeText(text).score,
+            getEmotionalTone: (text) => analyzeText(text).sentiment,
+            getTopWords: (text) => analyzeText(text).words
+        };
+    };
+  
+    // Re-use previous sentiment analysis functions
+    const { analyzeText, calculateSentimentScore, getEmotionalTone, getTopWords } = createSentimentAnalyzer(finalConfig);
+  
+    /**
+     * Fetches and extracts content from web pages
+     * 
+     * @param {string} url - URL to analyze
+     * @returns {Promise<string>} Extracted text content
+     * 
+     * Implementation Notes:
+     * - Uses progressive enhancement for content selection
+     * - Implements fallback strategies for content extraction
+     * - Handles various DOM structures
+     * 
+     * Potential Enhancements:
+     * - Add support for dynamic content (SPA)
+     * - Implement content cleaning rules
+     * - Add support for paywalled content
+     * - Handle rate limiting
+     */
+    const fetchContent = async (url) => {
+        try {
+            const response = await fetch(url);
+            const html = await response.text();
+            
+            const dom = new JSDOM(html);
+            const doc = dom.window.document;
+            
+            // Enhanced content selectors
+            const contentSelectors = [
+                'article',
+                'main',
+                '.content',
+                '.post-content',
+                '.entry-content',
+                '.article-content',
+                '.blog-post',
+                '.post',
+                'article p',
+                '.content p',
+                'p'
+            ];
+            
+            let content = '';
+            for (const selector of contentSelectors) {
+                const elements = doc.querySelectorAll(selector);
+                if (elements.length) {
+                    elements.forEach(el => {
+                        // Skip if element contains mostly navigation/header/footer content
+                        if (el.closest('nav') || el.closest('header') || el.closest('footer')) {
+                            return;
+                        }
+                        content += el.textContent + '\n\n';
+                    });
+                    if (content.trim().length > 0) break;
+                }
+            }
+            
+            // If no content was found through selectors, get all text content
+            if (!content) {
+                content = doc.body.textContent || '';
+            }
+            
+            // Clean up the content
+            content = content
+                .replace(/\s+/g, ' ')
+                .replace(/\n\s*\n/g, '\n\n')
+                .trim();
+                
+            // Ensure we're returning a string
+            return content || '';
+            
+        } catch (error) {
+            console.error('Fetch error:', error);
+            throw new Error(`Failed to fetch content: ${error.message}`);
+        }
+    };
+  
+    /**
+     * Extracts metadata from web documents
+     * 
+     * @param {Document} doc - DOM document
+     * @returns {Object} Extracted metadata
+     * 
+     * Implementation Notes:
+     * - Supports multiple metadata formats (meta tags, OpenGraph, etc.)
+     * - Uses fallback strategies for missing data
+     * 
+     * Potential Improvements:
+     * - Add schema.org parsing
+     * - Support more metadata formats
+     * - Add validation and cleaning
+     */
+    const extractMetadata = (doc) => {
+      const metadata = {
+        title: '',
+        description: '',
+        author: '',
+        date: '',
+        keywords: []
+      };
+  
+      // Extract meta tags with enhanced selectors
+      const metaTags = doc.querySelectorAll('meta');
+      metaTags.forEach(tag => {
+        const name = tag.getAttribute('name')?.toLowerCase();
+        const property = tag.getAttribute('property')?.toLowerCase();
+        const content = tag.getAttribute('content');
+  
+        if (content) {
+          if (name === 'description' || property === 'og:description') {
+            metadata.description = content;
+          }
+          if (name === 'author' || property === 'article:author') {
+            metadata.author = content;
+          }
+          if (name === 'keywords') {
+            metadata.keywords = content.split(',').map(k => k.trim());
+          }
+          if (name === 'date' || property === 'article:published_time' || 
+              property === 'article:modified_time') {
+            metadata.date = content;
+          }
+        }
+      });
+  
+      // Try different title sources
+      metadata.title = doc.querySelector('meta[property="og:title"]')?.getAttribute('content') ||
+                      doc.querySelector('h1')?.textContent ||
+                      doc.title || '';
+  
+      // Try to find author in structured data
+      const authorElement = doc.querySelector('[rel="author"], .author, .byline');
+      if (authorElement && !metadata.author) {
+        metadata.author = authorElement.textContent.trim();
+      }
+  
+      // Try to find date in structured data
+      if (!metadata.date) {
+        const dateElement = doc.querySelector('time, .date, .published');
+        if (dateElement) {
+          metadata.date = dateElement.getAttribute('datetime') || dateElement.textContent.trim();
+        }
+      }
+  
+      return metadata;
+    };
+  
+    /**
+     * Analyzes sentiment of web page content
+     * 
+     * @param {string} url - URL to analyze
+     * @returns {Promise<Object>} Complete analysis results
+     * 
+     * Potential Enhancements:
+     * - Add caching
+     * - Implement batch processing
+     * - Add historical tracking
+     */
+    const analyzeUrl = async (url) => {
+        try {
+            const content = await fetchContent(url);
+            
+            if (!content) {
+                console.warn(`No content found for URL: ${url}`);
+                return {
+                    score: 0,
+                    words: [],
+                    summary: { positive: 0, negative: 0, neutral: 0 },
+                    sentiment: 'Neutral',
+                    topEmotions: [],
+                    intensity: 'None',
+                    wordCount: 0,
+                    url,
+                    metadata: {},
+                    fetchDate: new Date().toISOString()
+                };
+            }
+
+            const analysis = analyzeText(content);
+            
+            // Create a new JSDOM instance for metadata extraction
+            const response = await fetch(url);
+            const html = await response.text();
+            const dom = new JSDOM(html);
+            
+            // Additional URL-specific analysis
+            analysis.url = url;
+            analysis.metadata = extractMetadata(dom.window.document);
+            analysis.fetchDate = new Date().toISOString();
+            
+            return analysis;
+        } catch (error) {
+            console.error('Analysis error:', error);
+            throw new Error(`Analysis failed: ${error.message}`);
+        }
+    };
+  
+    // Enhanced API
+    return {
+      analyzeText,
+      analyzeUrl,
+      addPositiveWords: (words) => words.forEach(word => finalConfig.positiveWords.add(word)),
+      addNegativeWords: (words) => words.forEach(word => finalConfig.negativeWords.add(word)),
+      addIntensifier: (word, multiplier) => finalConfig.intensifiers.set(word, multiplier),
+      addNegator: (word) => finalConfig.negators.add(word),
+      getConfig: () => ({ ...finalConfig }),
+      getDictionaries: () => ({
+        positiveCount: finalConfig.positiveWords.size,
+        negativeCount: finalConfig.negativeWords.size,
+        intensifierCount: finalConfig.intensifiers.size,
+        negatorCount: finalConfig.negators.size
+      })
+    };
+  };
+  
+  // Example usage:
+  const analyzer = createWebSentimentAnalyzer();
+  
+  /**
+   * Creates a visual representation of sentiment score
+   * 
+   * @param {number} score - Sentiment score to visualize
+   * @returns {string} ASCII visualization of sentiment scale
+   * 
+   * Design Notes:
+   * - Uses Unicode characters for better visualization
+   * - Implements fixed-width scale for consistent display
+   * 
+   * Potential Enhancements:
+   * - Add color support
+   * - Implement alternative visualizations
+   * - Add interactive elements
+   */
+  const createSentimentScale = (score) => {
+    const width = 40; // Width of the scale
+    const middle = Math.floor(width / 2);
+    // Clamp score between -10 and 10 for display purposes
+    const clampedScore = Math.max(-10, Math.min(10, score));
+    const position = Math.round(middle + (clampedScore * middle / 10));
+    
+    let scale = '';
+    for (let i = 0; i < width; i++) {
+        if (i === middle) scale += '│'; // Using Unicode box drawing character
+        else if (i === position) scale += '●';
+        else scale += '─';
+    }
+    
+    // Simpler scale display without arrows and extra spacing
+    return `
+NEGATIVE ${' '.repeat(middle-5)}NEUTRAL${' '.repeat(middle-5)} POSITIVE
+[-10] ${scale} [+10]
+Score: ${score.toFixed(2)}
+`;
+  };
+
+  /**
+   * Formats analysis results for human readability
+   * 
+   * @param {Object} analysis - Analysis results to format
+   * @returns {string} Formatted analysis report
+   * 
+   * Implementation Notes:
+   * - Uses structured format for consistency
+   * - Implements progressive disclosure of details
+   * 
+   * Potential Improvements:
+   * - Add output format options (JSON, CSV, etc.)
+   * - Implement templating system
+   * - Add internationalization support
+   */
+  const formatAnalysisResults = (analysis) => {
+    const {
+        score,
+        summary,
+        sentiment,
+        topEmotions,
+        intensity,
+        wordCount,
+        metadata,
+        url
+    } = analysis;
+
+    return `
+=== Sentiment Analysis for ${metadata.title || url} ===
+
+${createSentimentScale(score)}
+
+Overall Assessment:
+• Sentiment: ${sentiment} (${intensity})
+• Total Words Analyzed: ${wordCount}
+
+Word Breakdown:
+• Positive Words: ${summary.positive}
+• Negative Words: ${summary.negative}
+• Neutral Words: ${summary.neutral}
+
+${topEmotions.length ? `Dominant Emotions:
+${topEmotions.map(e => `• ${e.emotion} (mentioned ${e.count} time${e.count > 1 ? 's' : ''})`).join('\n')}` : ''}
+
+Content Details:
+• Author: ${metadata.author || 'Not specified'}
+• Date: ${metadata.date || 'Not specified'}
+${metadata.description ? `• Description: ${metadata.description}` : ''}
+
+Notable Words:
+${analysis.words
+    .filter(w => w.score !== 0)
+    .slice(0, 5)
+    .map(w => `• "${w.word}" (${w.score > 0 ? 'positive' : 'negative'}, ${w.category || 'general'})`)
+    .join('\n')}
+
+${'-'.repeat(60)}
+`;
+  };
+
+  // Update the analyzeWebPage function
+  const analyzeWebPage = async (url) => {
+    try {
+        const analysis = await analyzer.analyzeUrl(url);
+        console.log(formatAnalysisResults(analysis));
+    } catch (error) {
+        console.error(`\n❌ Analysis failed for ${url}:`, error.message);
+    }
+  };
+  
+  // Example:
+  // analyzeWebPage('https://example.com/blog-post');
+  
+  // Add custom words
+//   analyzer.addPositiveWords(['groundbreaking', 'game-changing']);
+//   analyzer.addNegativeWords(['concerning', 'questionable']);
+//   analyzer.addIntensifier('incredibly', 1.8);
+//   analyzer.addNegator('lacks');
+  
+//   // Get dictionary stats
+//   console.log(analyzer.getDictionaries());
+
+// Remove the hard-coded URLs and add CLI handling
+const helpText = `
+Sentiment Analyzer
+=================
+
+Analyzes the sentiment of web pages and provides detailed emotional analysis.
+
+Usage:
+  bun run app.js <url>
+  bun run app.js <url1> <url2> <url3> ...
+
+Example:
+  bun run app.js https://example.com/blog-post
+  bun run app.js https://blog1.com https://blog2.com
+
+Options:
+  --help, -h    Show this help message
+`;
+
+/**
+ * CLI program entry point
+ * 
+ * Implementation Notes:
+ * - Uses async/await for proper error handling
+ * - Implements command pattern for URL processing
+ * 
+ * Potential Enhancements:
+ * - Add configuration file support
+ * - Implement batch processing from file
+ * - Add progress indicators
+ * - Add output formatting options
+ */
+const main = async () => {
+    // Get command line arguments (skip first two as they're node/bun and script path)
+    const args = process.argv.slice(2);
+
+    // Show help if no arguments or help flag
+    if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
+        console.log(helpText);
+        return;
+    }
+
+    // Create analyzer instance
+    const analyzer = createWebSentimentAnalyzer();
+
+    // Analyze each URL
+    for (const url of args) {
+        try {
+            // Skip any help flags that might have been passed
+            if (url.startsWith('-')) continue;
+            
+            await analyzeWebPage(url);
+        } catch (error) {
+            console.error(`\n❌ Failed to analyze ${url}:`, error.message);
+        }
+    }
+};
+
+// Run the program
+main().catch(error => {
+    console.error('Fatal error:', error);
+    process.exit(1);
+});
\ No newline at end of file
diff --git a/js/sentiment/bun.lockb b/js/sentiment/bun.lockb
new file mode 100755
index 0000000..e7e3ab3
--- /dev/null
+++ b/js/sentiment/bun.lockb
Binary files differdiff --git a/js/sentiment/jsconfig.json b/js/sentiment/jsconfig.json
new file mode 100644
index 0000000..238655f
--- /dev/null
+++ b/js/sentiment/jsconfig.json
@@ -0,0 +1,27 @@
+{
+  "compilerOptions": {
+    // Enable latest features
+    "lib": ["ESNext", "DOM"],
+    "target": "ESNext",
+    "module": "ESNext",
+    "moduleDetection": "force",
+    "jsx": "react-jsx",
+    "allowJs": true,
+
+    // Bundler mode
+    "moduleResolution": "bundler",
+    "allowImportingTsExtensions": true,
+    "verbatimModuleSyntax": true,
+    "noEmit": true,
+
+    // Best practices
+    "strict": true,
+    "skipLibCheck": true,
+    "noFallthroughCasesInSwitch": true,
+
+    // Some stricter flags (disabled by default)
+    "noUnusedLocals": false,
+    "noUnusedParameters": false,
+    "noPropertyAccessFromIndexSignature": false
+  }
+}
diff --git a/js/sentiment/package.json b/js/sentiment/package.json
new file mode 100644
index 0000000..c55b3ee
--- /dev/null
+++ b/js/sentiment/package.json
@@ -0,0 +1,14 @@
+{
+  "name": "sentiment",
+  "module": "app.js",
+  "type": "module",
+  "devDependencies": {
+    "@types/bun": "latest"
+  },
+  "peerDependencies": {
+    "typescript": "^5.0.0"
+  },
+  "dependencies": {
+    "jsdom": "^26.0.0"
+  }
+}
\ No newline at end of file
aa0243192c922c977f41ce549e42'>887ff65 ^
6c36e04 ^

b0bf09b ^



2b3e123 ^
6c36e04 ^
67fb093 ^


6c36e04 ^


6c36e04 ^



6c36e04 ^

1d04c2a ^
6c36e04 ^

6c36e04 ^
0ef4b6f ^
67fb093 ^



6c36e04 ^
67fb093 ^




6c36e04 ^
67fb093 ^















0ef4b6f ^
67fb093 ^
























92dc31b ^
6c36e04 ^
67fb093 ^
ceeb30a ^


2559ebf ^

ceeb30a ^


67fb093 ^
29de329 ^



67fb093 ^

59df06f ^
29de329 ^






cef784b ^
29de329 ^



1d04c2a ^
29de329 ^

7899d15 ^


bb620e0 ^
7899d15 ^




6c36e04 ^
7899d15 ^
6c36e04 ^
29de329 ^
7899d15 ^
bb620e0 ^



























7899d15 ^













bb620e0 ^
cef784b ^


6c36e04 ^

7899d15 ^














c9a909f ^
7899d15 ^






























0ee7d30 ^



7899d15 ^

0ee7d30 ^















7899d15 ^






3338dce ^











bb46b2b ^
bb46b2b ^
887ff65 ^

bb46b2b ^
29de329 ^
887ff65 ^



















a974027 ^
887ff65 ^
3338dce ^
887ff65 ^


bb46b2b ^

f37508a ^














0a52124 ^










f4b7741 ^
0ceea02 ^
f4b7741 ^
0ceea02 ^



f4b7741 ^
0a52124 ^


f4b7741 ^


fad375c ^


f4b7741 ^








0a52124 ^


f4b7741 ^























67fb093 ^










bb46b2b ^
3338dce ^


bb46b2b ^

577248f ^
577248f ^













f6216bb ^


3338dce ^




f6216bb ^






577248f ^
2a4dd5c ^









3338dce ^
2a4dd5c ^




577248f ^
bb46b2b ^
2c486cb ^





bb46b2b ^




887ff65 ^
7899d15 ^
a669233 ^
7899d15 ^





bb46b2b ^

7899d15 ^
887ff65 ^






d851890 ^
887ff65 ^

7899d15 ^






887ff65 ^
bb46b2b ^



















1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907