Master practical NLP tasks using AI APIs: sentiment analysis, entity recognition, text classification, summarization, and language detection. Build production-ready text analysis systems.
Text analysis and Natural Language Processing (NLP) unlock insights from unstructured text data - one of the most valuable and abundant data sources in modern applications. From analyzing customer feedback to extracting key information from documents, NLP powers intelligent features that make applications smarter and more useful.
Unlike the content generation we've learned, text analysis focuses on understanding and extracting insights from existing text. These capabilities are essential for building intelligent systems that can process, categorize, and derive meaning from text at scale.
In this lesson, you'll master practical NLP tasks using AI APIs. You'll learn to analyze sentiment, extract entities, classify text, summarize documents, and detect languages - all without needing deep ML expertise. These are production-ready techniques used by real-world applications serving millions of users.
Sentiment analysis determines the emotional tone of text - essential for understanding customer feedback, social media monitoring, and content analysis.
What is Sentiment Analysis?
Sentiment analysis (opinion mining) extracts subjective information from text:
Use Cases:
1. Customer Feedback Analysis:
2. Social Media Monitoring:
3. Market Research:
4. Content Moderation:
Implementation Approaches:
Approach 1: Direct Analysis
Ask the AI model to analyze sentiment directly.
1async function analyzeSentiment(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: "Analyze the sentiment of the provided text. Respond with: POSITIVE, NEGATIVE, or NEUTRAL."
7 }, {
8 role: "user",
9 content: text
10 }],
11 temperature: 0.2, // Low for consistent classification
12 max_tokens: 10
13 });
14
15 return completion.choices[0].message.content.trim();
16}Approach 2: Structured Analysis with JSON
Get detailed sentiment breakdown.
1async function analyzeSentimentDetailed(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Analyze sentiment and return JSON:
7{
8 "overall": "positive/negative/neutral",
9 "score": -1.0 to 1.0,
10 "confidence": 0.0 to 1.0,
11 "emotions": {
12 "joy": 0.0 to 1.0,
13 "anger": 0.0 to 1.0,
14 "sadness": 0.0 to 1.0,
15 "fear": 0.0 to 1.0,
16 "surprise": 0.0 to 1.0
17 },
18 "aspects": [
19 {"aspect": "feature name", "sentiment": "positive/negative"}
20 ]
21}`
22 }, {
23 role: "user",
24 content: text
25 }],
26 response_format: { type: "json_object" },
27 temperature: 0.2
28 });
29
30 return JSON.parse(completion.choices[0].message.content);
31}Approach 3: Batch Processing
Analyze multiple texts efficiently.
1async function analyzeSentimentBatch(texts) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: `Analyze sentiment for each text and return JSON array:
7{
8 "results": [
9 {"id": 0, "sentiment": "positive/negative/neutral", "score": -1.0 to 1.0}
10 ]
11}`
12 }, {
13 role: "user",
14 content: JSON.stringify(texts.map((text, id) => ({ id, text })))
15 }],
16 response_format: { type: "json_object" },
17 temperature: 0.2
18 });
19
20 return JSON.parse(completion.choices[0].message.content);
21}Best Practices:
1. Use Low Temperature:
2. Provide Context:
3. Handle Edge Cases:
4. Validate Results:
5. Consider Domain Adaptation:
Sentiment Analysis Pipeline:
1Input Text
2 ↓
3Preprocessing (clean, normalize)
4 ↓
5Sentiment Analysis API Call
6 ↓
7Parse and Validate Results
8 ↓
9Store Results (database)
10 ↓
11Aggregate and Visualize
12 ↓
13Action/Alerts (if needed)Common Pitfalls:
❌ Don't: Rely on simple keyword matching
✅ Do: Use context-aware AI analysis
❌ Don't: Ignore sarcasm and irony
✅ Do: Test with complex examples
❌ Don't: Use high temperature
✅ Do: Keep temperature 0.1-0.3 for consistency
❌ Don't: Forget to aggregate results
✅ Do: Track trends over time
Named Entity Recognition (NER) identifies and classifies named entities in text - people, organizations, locations, dates, and more. Essential for information extraction and knowledge graph construction.
What is NER?
NER identifies and categorizes key information:
Use Cases:
1. Document Processing:
2. Customer Support:
3. Content Analysis:
4. Business Intelligence:
Implementation:
Basic Entity Extraction:
1async function extractEntities(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Extract named entities as JSON:
7{
8 "people": ["names"],
9 "organizations": ["companies/orgs"],
10 "locations": ["places"],
11 "dates": ["dates"],
12 "products": ["product names"],
13 "emails": ["emails"],
14 "phones": ["phone numbers"]
15}`
16 }, {
17 role: "user",
18 content: text
19 }],
20 response_format: { type: "json_object" },
21 temperature: 0.2
22 });
23
24 return JSON.parse(completion.choices[0].message.content);
25}
26
27// Usage
28const entities = await extractEntities(
29 "Sarah Johnson from TechCorp will visit our Boston office on March 15th. " +
30 "Contact her at [email protected] or 555-0123."
31);
32
33console.log(entities);
34// {
35// people: ["Sarah Johnson"],
36// organizations: ["TechCorp"],
37// locations: ["Boston"],
38// dates: ["March 15th"],
39// emails: ["[email protected]"],
40// phones: ["555-0123"]
41// }Advanced: Relationship Extraction:
1async function extractRelationships(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Extract entities and their relationships as JSON:
7{
8 "entities": [
9 {"id": "unique_id", "type": "PERSON/ORG/LOCATION", "value": "name"}
10 ],
11 "relationships": [
12 {"from": "entity_id", "to": "entity_id", "type": "works_at/located_in/etc"}
13 ]
14}`
15 }, {
16 role: "user",
17 content: text
18 }],
19 response_format: { type: "json_object" },
20 temperature: 0.2
21 });
22
23 return JSON.parse(completion.choices[0].message.content);
24}Resume Parsing Example:
1async function parseResume(resumeText) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Parse resume and extract structured data as JSON:
7{
8 "name": "full name",
9 "email": "email",
10 "phone": "phone",
11 "location": "city, state",
12 "summary": "professional summary",
13 "experience": [
14 {
15 "company": "company name",
16 "title": "job title",
17 "startDate": "date",
18 "endDate": "date or Present",
19 "description": "role description"
20 }
21 ],
22 "education": [
23 {
24 "school": "school name",
25 "degree": "degree type",
26 "field": "field of study",
27 "graduationDate": "date"
28 }
29 ],
30 "skills": ["skill1", "skill2"]
31}`
32 }, {
33 role: "user",
34 content: resumeText
35 }],
36 response_format: { type: "json_object" },
37 temperature: 0.2
38 });
39
40 return JSON.parse(completion.choices[0].message.content);
41}Best Practices:
1. Be Specific About Entity Types:
2. Normalize Extracted Data:
3. Handle Ambiguity:
4. Validate Extractions:
5. Combine with Databases:
Text classification assigns predefined categories to text documents - essential for content organization, spam detection, and automated routing.
What is Text Classification?
Text classification (text categorization) assigns one or more labels to text:
Use Cases:
1. Content Management:
2. Customer Support:
3. Email Management:
4. Social Media:
5. E-commerce:
Implementation Approaches:
Approach 1: Simple Classification
1async function classifyText(text, categories) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: `Classify the text into ONE of these categories: ${categories.join(', ')}.
7Respond with ONLY the category name.`
8 }, {
9 role: "user",
10 content: text
11 }],
12 temperature: 0.1, // Very low for consistent classification
13 max_tokens: 20
14 });
15
16 return completion.choices[0].message.content.trim();
17}
18
19// Usage
20const category = await classifyText(
21 "Scientists discover new exoplanet with potential for life",
22 ["Technology", "Science", "Business", "Sports", "Entertainment"]
23);
24console.log(category); // "Science"Approach 2: Multi-Label Classification with Confidence
1async function classifyTextMultiLabel(text, categories) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Classify text into one or more categories. Return JSON:
7{
8 "categories": [
9 {"name": "category", "confidence": 0.0-1.0, "primary": true/false}
10 ]
11}
12
13Available categories: ${categories.join(', ')}`
14 }, {
15 role: "user",
16 content: text
17 }],
18 response_format: { type: "json_object" },
19 temperature: 0.2
20 });
21
22 return JSON.parse(completion.choices[0].message.content);
23}Approach 3: Hierarchical Classification
1async function classifyHierarchical(text, taxonomy) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Classify text using this hierarchical taxonomy and return JSON:
7{
8 "path": ["Level1", "Level2", "Level3"],
9 "confidence": 0.0-1.0
10}
11
12Taxonomy:
13${JSON.stringify(taxonomy, null, 2)}`
14 }, {
15 role: "user",
16 content: text
17 }],
18 response_format: { type: "json_object" },
19 temperature: 0.2
20 });
21
22 return JSON.parse(completion.choices[0].message.content);
23}
24
25// Example taxonomy
26const taxonomy = {
27 "Technology": {
28 "Artificial Intelligence": ["Machine Learning", "Computer Vision", "NLP"],
29 "Web Development": ["Frontend", "Backend", "DevOps"],
30 "Mobile": ["iOS", "Android", "Cross-platform"]
31 },
32 "Business": {
33 "Startups": ["Fundraising", "Growth", "Strategy"],
34 "Enterprise": ["Management", "Operations", "Strategy"]
35 }
36};Real-World Examples:
Support Ticket Routing:
1async function routeTicket(ticketText) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: `Classify support ticket and return JSON:
7{
8 "category": "Technical/Billing/Account/General",
9 "priority": "High/Medium/Low",
10 "department": "Engineering/Finance/CustomerSuccess/Sales",
11 "suggestedAction": "brief action"
12}`
13 }, {
14 role: "user",
15 content: ticketText
16 }],
17 response_format: { type: "json_object" },
18 temperature: 0.2
19 });
20
21 return JSON.parse(completion.choices[0].message.content);
22}Spam Detection:
1async function detectSpam(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: `Analyze if text is spam and return JSON:
7{
8 "isSpam": true/false,
9 "confidence": 0.0-1.0,
10 "reasons": ["reason1", "reason2"],
11 "spamType": "phishing/marketing/scam/none"
12}`
13 }, {
14 role: "user",
15 content: text
16 }],
17 response_format: { type: "json_object" },
18 temperature: 0.1
19 });
20
21 return JSON.parse(completion.choices[0].message.content);
22}Best Practices:
1. Define Clear Categories:
2. Use Consistent Temperature:
3. Provide Few-Shot Examples:
1const systemPrompt = `Classify text into categories.
2
3Examples:
4Text: "New iPhone released with better camera"
5Category: Technology
6
7Text: "Stock market hits all-time high"
8Category: Business
9
10Text: "Team wins championship game"
11Category: Sports
12
13Now classify:`;4. Handle Ambiguous Cases:
5. Batch Processing:
1async function classifyBatch(texts, categories) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: `Classify each text and return JSON array:
7{
8 "results": [
9 {"id": 0, "category": "category_name", "confidence": 0.0-1.0}
10 ]
11}
12
13Categories: ${categories.join(', ')}`
14 }, {
15 role: "user",
16 content: JSON.stringify(texts.map((text, id) => ({ id, text })))
17 }],
18 response_format: { type: "json_object" },
19 temperature: 0.1
20 });
21
22 return JSON.parse(completion.choices[0].message.content);
23}Classification Pipeline:
1Input Text
2 ↓
3Preprocessing (clean, normalize)
4 ↓
5Feature Extraction (optional)
6 ↓
7Classification API Call
8 ↓
9Parse Results
10 ↓
11Validate (confidence thresholds)
12 ↓
13Route/Store/Display
14 ↓
15Monitor AccuracyText summarization condenses long documents into concise summaries - essential for information overload, report generation, and quick insights.
Types of Summarization:
1. Extractive Summarization:
2. Abstractive Summarization:
Use Cases:
1. Content Consumption:
2. Business Intelligence:
3. Document Management:
4. Customer Support:
Implementation:
Basic Summarization:
1async function summarizeText(text, maxWords = 100) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Summarize the provided text in approximately ${maxWords} words.
7Focus on key points and main ideas. Be concise and clear.`
8 }, {
9 role: "user",
10 content: text
11 }],
12 temperature: 0.3,
13 max_tokens: Math.ceil(maxWords * 1.5) // Buffer for tokens
14 });
15
16 return completion.choices[0].message.content;
17}Structured Summarization:
1async function summarizeStructured(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Summarize the text and return JSON:
7{
8 "summary": "brief 1-2 sentence summary",
9 "keyPoints": ["point1", "point2", "point3"],
10 "mainTopics": ["topic1", "topic2"],
11 "actionItems": ["action1", "action2"] (if applicable),
12 "sentiment": "positive/negative/neutral",
13 "readingTime": minutes (original),
14 "wordCount": count (original)
15}`
16 }, {
17 role: "user",
18 content: text
19 }],
20 response_format: { type: "json_object" },
21 temperature: 0.3
22 });
23
24 return JSON.parse(completion.choices[0].message.content);
25}Multi-Length Summarization:
1async function summarizeMultiLength(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Create multiple summaries of different lengths and return JSON:
7{
8 "oneLine": "single sentence summary",
9 "short": "2-3 sentence summary",
10 "medium": "1 paragraph summary",
11 "detailed": "2-3 paragraph summary with key points"
12}`
13 }, {
14 role: "user",
15 content: text
16 }],
17 response_format: { type: "json_object" },
18 temperature: 0.3
19 });
20
21 return JSON.parse(completion.choices[0].message.content);
22}Meeting Minutes:
1async function generateMeetingMinutes(transcript) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Generate meeting minutes from transcript. Return JSON:
7{
8 "title": "meeting topic",
9 "date": "date mentioned or null",
10 "attendees": ["list of people mentioned"],
11 "summary": "brief overview",
12 "keyDiscussions": [
13 {"topic": "topic", "summary": "what was discussed"}
14 ],
15 "decisions": ["decision1", "decision2"],
16 "actionItems": [
17 {"task": "description", "owner": "person or null", "deadline": "date or null"}
18 ],
19 "nextSteps": ["step1", "step2"]
20}`
21 }, {
22 role: "user",
23 content: transcript
24 }],
25 response_format: { type: "json_object" },
26 temperature: 0.2
27 });
28
29 return JSON.parse(completion.choices[0].message.content);
30}Customer Feedback Summary:
1async function summarizeFeedback(feedbackArray) {
2 const combined = feedbackArray.join('\n\n---\n\n');
3
4 const completion = await openai.chat.completions.create({
5 model: "gpt-4",
6 messages: [{
7 role: "system",
8 content: `Analyze customer feedback and return JSON:
9{
10 "overallSentiment": "positive/negative/mixed",
11 "commonThemes": [
12 {"theme": "theme name", "mentions": count, "sentiment": "pos/neg/neutral"}
13 ],
14 "keyIssues": ["issue1", "issue2"],
15 "positiveHighlights": ["highlight1", "highlight2"],
16 "recommendations": ["recommendation1", "recommendation2"],
17 "urgentMatters": ["urgent issue or null"]
18}`
19 }, {
20 role: "user",
21 content: combined
22 }],
23 response_format: { type: "json_object" },
24 temperature: 0.3
25 });
26
27 return JSON.parse(completion.choices[0].message.content);
28}Best Practices:
1. Define Summary Length:
2. Focus on Key Information:
3. Preserve Accuracy:
4. Handle Long Documents:
1async function summarizeLongDocument(text, chunkSize = 3000) {
2 // Split into chunks
3 const chunks = splitIntoChunks(text, chunkSize);
4
5 // Summarize each chunk
6 const chunkSummaries = await Promise.all(
7 chunks.map(chunk => summarizeText(chunk, 200))
8 );
9
10 // Combine and final summarize
11 const combined = chunkSummaries.join('\n\n');
12 return await summarizeText(combined, 300);
13}
14
15function splitIntoChunks(text, chunkSize) {
16 const words = text.split(' ');
17 const chunks = [];
18
19 for (let i = 0; i < words.length; i += chunkSize) {
20 chunks.push(words.slice(i, i + chunkSize).join(' '));
21 }
22
23 return chunks;
24}5. Add Context When Needed:
1const prompt = `Summarize this customer support conversation.
2Focus on the customer's issue and the resolution provided.
3
4Conversation:
5${text}`;Quality Checks:
Language detection identifies the language of text - essential for internationalization, content routing, and multi-language applications.
What is Language Detection?
Language detection (language identification) determines which language text is written in:
Use Cases:
1. Content Management:
2. Customer Support:
3. Social Media:
4. E-commerce:
Implementation:
Simple Language Detection:
1async function detectLanguage(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: "Detect the language of the provided text. Respond with ONLY the language name (e.g., English, Spanish, French, etc.)."
7 }, {
8 role: "user",
9 content: text
10 }],
11 temperature: 0.1,
12 max_tokens: 10
13 });
14
15 return completion.choices[0].message.content.trim();
16}
17
18// Usage
19const lang = await detectLanguage("Bonjour, comment allez-vous?");
20console.log(lang); // "French"Detailed Language Analysis:
1async function analyzeLanguage(text) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Analyze the language(s) in the text and return JSON:
7{
8 "primaryLanguage": "language name",
9 "languageCode": "ISO 639-1 code (e.g., en, es, fr)",
10 "confidence": 0.0-1.0,
11 "multiLanguage": true/false,
12 "languages": [
13 {"language": "name", "percentage": 0-100}
14 ],
15 "script": "Latin/Cyrillic/Arabic/etc",
16 "dialect": "dialect or null (e.g., British English, Mexican Spanish)"
17}`
18 }, {
19 role: "user",
20 content: text
21 }],
22 response_format: { type: "json_object" },
23 temperature: 0.1
24 });
25
26 return JSON.parse(completion.choices[0].message.content);
27}Multi-Language Content Processing:
1async function processMultiLanguageContent(text) {
2 // Detect language
3 const langInfo = await analyzeLanguage(text);
4
5 // Process based on language
6 if (langInfo.primaryLanguage !== "English") {
7 // Translate to English for processing
8 const translated = await translateText(text, langInfo.languageCode, "en");
9
10 // Analyze in English
11 const analysis = {
12 originalLanguage: langInfo.primaryLanguage,
13 translatedText: translated,
14 sentiment: await analyzeSentiment(translated),
15 entities: await extractEntities(translated)
16 };
17
18 return analysis;
19 } else {
20 // Process directly
21 return {
22 originalLanguage: "English",
23 sentiment: await analyzeSentiment(text),
24 entities: await extractEntities(text)
25 };
26 }
27}Language-Based Routing:
1async function routeByLanguage(text, supportedLanguages) {
2 const langInfo = await analyzeLanguage(text);
3
4 const routing = {
5 language: langInfo.primaryLanguage,
6 languageCode: langInfo.languageCode,
7 supported: supportedLanguages.includes(langInfo.languageCode),
8 action: null
9 };
10
11 if (routing.supported) {
12 routing.action = `route_to_${langInfo.languageCode}_support`;
13 } else {
14 routing.action = "route_to_translation_service";
15 }
16
17 return routing;
18}
19
20// Usage
21const routing = await routeByLanguage(
22 "Necesito ayuda con mi pedido",
23 ["en", "es", "fr"]
24);
25console.log(routing);
26// { language: "Spanish", languageCode: "es", supported: true, action: "route_to_es_support" }Translation Helper:
1async function translateText(text, fromLang, toLang) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-4",
4 messages: [{
5 role: "system",
6 content: `Translate the text from ${fromLang} to ${toLang}.
7Maintain tone and context. Return ONLY the translated text.`
8 }, {
9 role: "user",
10 content: text
11 }],
12 temperature: 0.3
13 });
14
15 return completion.choices[0].message.content;
16}Batch Language Detection:
1async function detectLanguagesBatch(texts) {
2 const completion = await openai.chat.completions.create({
3 model: "gpt-3.5-turbo",
4 messages: [{
5 role: "system",
6 content: `Detect language for each text and return JSON:
7{
8 "results": [
9 {"id": 0, "language": "name", "code": "ISO code"}
10 ]
11}`
12 }, {
13 role: "user",
14 content: JSON.stringify(texts.map((text, id) => ({ id, text })))
15 }],
16 response_format: { type: "json_object" },
17 temperature: 0.1
18 });
19
20 return JSON.parse(completion.choices[0].message.content);
21}Best Practices:
1. Handle Mixed Language:
2. Use Language Codes:
3. Consider Dialects:
4. Optimize for Performance:
5. Provide Fallbacks:
Common Languages:
A comprehensive text analysis tool demonstrating all NLP tasks from Lesson 6: sentiment analysis, entity extraction, text classification, summarization, and language detection. Professional-grade interface with real-time processing.
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>NLP Analysis Suite</title>
7</head>
8<body>
9 <div class="container">
10 <header class="hero">
11 <h1>🔍 NLP Analysis Suite</h1>
12 <p class="subtitle">Professional text analysis and natural language processing toolkit</p>
13 </header>
14
15 <!-- Task Selector -->
16 <section class="card">
17 <h2>📋 Select Analysis Task</h2>
18 <div class="task-selector">
19 <button class="task-btn active" onclick="selectTask('sentiment')" data-task="sentiment">
20 😊 Sentiment Analysis
21 </button>
22 <button class="task-btn" onclick="selectTask('entities')" data-task="entities">
23 🏷️ Entity Extraction
24 </button>
25 <button class="task-btn" onclick="selectTask('classification')" data-task="classification">
26 📁 Text Classification
27 </button>
28 <button class="task-btn" onclick="selectTask('summarization')" data-task="summarization">
29 📝 Summarization
30 </button>
31 <button class="task-btn" onclick="selectTask('language')" data-task="language">
32 🌍 Language Detection
33 </button>
34 </div>
35 </section>
36
37 <!-- Sentiment Analysis -->
38 <section id="sentiment-panel" class="card analysis-panel">
39 <h2>😊 Sentiment Analysis</h2>
40 <p>Analyze the emotional tone and sentiment of text</p>
41
42 <div class="form-group">
43 <label>Text to Analyze:</label>
44 <textarea id="sentiment-input" rows="5" placeholder="Enter text to analyze sentiment...">I absolutely love this product! The quality is amazing and customer service was incredibly helpful. Best purchase I've made this year!</textarea>
45 </div>
46
47 <div class="form-group">
48 <label>Analysis Type:</label>
49 <select id="sentiment-type">
50 <option value="simple">Simple (Positive/Negative/Neutral)</option>
51 <option value="detailed">Detailed with Emotions</option>
52 <option value="aspects">Aspect-Based</option>
53 </select>
54 </div>
55
56 <button class="btn btn-primary" onclick="analyzeSentiment()">Analyze Sentiment</button>
57
58 <div id="sentiment-results" class="results-panel hidden"></div>
59 </section>
60
61 <!-- Entity Extraction -->
62 <section id="entities-panel" class="card analysis-panel hidden">
63 <h2>🏷️ Named Entity Recognition</h2>
64 <p>Extract people, organizations, locations, dates, and more</p>
65
66 <div class="form-group">
67 <label>Text to Process:</label>
68 <textarea id="entities-input" rows="5" placeholder="Enter text to extract entities...">Sarah Johnson from TechCorp visited our Boston office on March 15th, 2024. She discussed the new AI product launch and sent a follow-up email to [email protected].</textarea>
69 </div>
70
71 <div class="form-group">
72 <label>Entity Types to Extract:</label>
73 <div class="checkbox-group">
74 <label><input type="checkbox" checked value="people"> People</label>
75 <label><input type="checkbox" checked value="organizations"> Organizations</label>
76 <label><input type="checkbox" checked value="locations"> Locations</label>
77 <label><input type="checkbox" checked value="dates"> Dates</label>
78 <label><input type="checkbox" checked value="emails"> Emails</label>
79 <label><input type="checkbox" checked value="phones"> Phone Numbers</label>
80 </div>
81 </div>
82
83 <button class="btn btn-primary" onclick="extractEntities()">Extract Entities</button>
84
85 <div id="entities-results" class="results-panel hidden"></div>
86 </section>
87
88 <!-- Text Classification -->
89 <section id="classification-panel" class="card analysis-panel hidden">
90 <h2>📁 Text Classification</h2>
91 <p>Automatically categorize and classify text content</p>
92
93 <div class="form-group">
94 <label>Text to Classify:</label>
95 <textarea id="classification-input" rows="5" placeholder="Enter text to classify...">Scientists at MIT have developed a new machine learning algorithm that can predict protein structures with 90% accuracy, potentially revolutionizing drug discovery.</textarea>
96 </div>
97
98 <div class="form-group">
99 <label>Classification Type:</label>
100 <select id="classification-type" onchange="updateCategories()">
101 <option value="news">News Category</option>
102 <option value="support">Support Ticket</option>
103 <option value="spam">Spam Detection</option>
104 <option value="sentiment">Sentiment</option>
105 <option value="custom">Custom Categories</option>
106 </select>
107 </div>
108
109 <div id="custom-categories" class="form-group hidden">
110 <label>Custom Categories (comma-separated):</label>
111 <input type="text" id="custom-categories-input" placeholder="Category1, Category2, Category3">
112 </div>
113
114 <button class="btn btn-primary" onclick="classifyText()">Classify Text</button>
115
116 <div id="classification-results" class="results-panel hidden"></div>
117 </section>
118
119 <!-- Summarization -->
120 <section id="summarization-panel" class="card analysis-panel hidden">
121 <h2>📝 Text Summarization</h2>
122 <p>Generate concise summaries of long documents</p>
123
124 <div class="form-group">
125 <label>Text to Summarize:</label>
126 <textarea id="summarization-input" rows="8" placeholder="Enter text to summarize...">Artificial intelligence has transformed the technology landscape over the past decade. Machine learning algorithms now power everything from recommendation systems to autonomous vehicles. Natural language processing enables computers to understand and generate human language with remarkable accuracy. Computer vision allows machines to interpret and analyze visual information from the world. These advances have been driven by improvements in deep learning architectures, increased computational power, and the availability of large datasets. Companies across industries are adopting AI to improve efficiency, reduce costs, and create new products and services. However, challenges remain including bias in AI systems, ethical considerations, and the need for explainability. As AI continues to evolve, it will be important to address these challenges while maximizing the benefits of this transformative technology.</textarea>
127 </div>
128
129 <div class="form-group">
130 <label>Summary Length:</label>
131 <select id="summary-length">
132 <option value="brief">Brief (1-2 sentences)</option>
133 <option value="short">Short (50-75 words)</option>
134 <option value="medium" selected>Medium (100-150 words)</option>
135 <option value="detailed">Detailed (200+ words)</option>
136 </select>
137 </div>
138
139 <div class="form-group">
140 <label>Summary Style:</label>
141 <select id="summary-style">
142 <option value="paragraph">Paragraph</option>
143 <option value="bullets">Bullet Points</option>
144 <option value="structured">Structured (with sections)</option>
145 </select>
146 </div>
147
148 <button class="btn btn-primary" onclick="summarizeText()">Generate Summary</button>
149
150 <div id="summarization-results" class="results-panel hidden"></div>
151 </section>
152
153 <!-- Language Detection -->
154 <section id="language-panel" class="card analysis-panel hidden">
155 <h2>🌍 Language Detection</h2>
156 <p>Identify the language of text automatically</p>
157
158 <div class="form-group">
159 <label>Text to Analyze:</label>
160 <textarea id="language-input" rows="5" placeholder="Enter text in any language...">Bonjour! Comment allez-vous aujourd'hui? J'espère que vous passez une excellente journée.</textarea>
161 </div>
162
163 <div class="form-group">
164 <label>Detection Mode:</label>
165 <select id="language-mode">
166 <option value="simple">Simple Detection</option>
167 <option value="detailed">Detailed Analysis</option>
168 <option value="multi">Multi-Language Detection</option>
169 </select>
170 </div>
171
172 <button class="btn btn-primary" onclick="detectLanguage()">Detect Language</button>
173
174 <div id="language-results" class="results-panel hidden"></div>
175 </section>
176
177 <!-- Sample Texts -->
178 <section class="card">
179 <h2>📄 Sample Texts</h2>
180 <p>Click to load sample texts for testing:</p>
181
182 <div class="samples-grid">
183 <div class="sample-card" onclick="loadSample('positive-review')">
184 <h3>Positive Review</h3>
185 <p>Customer feedback example</p>
186 </div>
187 <div class="sample-card" onclick="loadSample('news-article')">
188 <h3>News Article</h3>
189 <p>Technology news snippet</p>
190 </div>
191 <div class="sample-card" onclick="loadSample('support-ticket')">
192 <h3>Support Ticket</h3>
193 <p>Customer support request</p>
194 </div>
195 <div class="sample-card" onclick="loadSample('multilingual')">
196 <h3>Multi-Language</h3>
197 <p>Mixed language text</p>
198 </div>
199 <div class="sample-card" onclick="loadSample('long-document')">
200 <h3>Long Document</h3>
201 <p>Article for summarization</p>
202 </div>
203 <div class="sample-card" onclick="loadSample('resume')">
204 <h3>Resume</h3>
205 <p>Professional resume text</p>
206 </div>
207 </div>
208 </section>
209
210 <!-- Batch Processing -->
211 <section class="card">
212 <h2>⚡ Batch Processing</h2>
213 <p>Process multiple texts at once (demo)</p>
214
215 <div class="form-group">
216 <label>Texts (one per line):</label>
217 <textarea id="batch-input" rows="6" placeholder="Enter multiple texts, one per line...">This product is amazing!
218I'm very disappointed with the service.
219The quality exceeded my expectations.
220Terrible experience, would not recommend.</textarea>
221 </div>
222
223 <div class="form-group">
224 <label>Batch Task:</label>
225 <select id="batch-task">
226 <option value="sentiment">Sentiment Analysis</option>
227 <option value="classification">Classification</option>
228 <option value="language">Language Detection</option>
229 </select>
230 </div>
231
232 <button class="btn btn-primary" onclick="processBatch()">Process Batch</button>
233
234 <div id="batch-results" class="results-panel hidden"></div>
235 </section>
236
237 <!-- Best Practices -->
238 <section class="card tips-section">
239 <h2>💡 NLP Best Practices</h2>
240 <div class="tips-grid">
241 <div class="tip-card">
242 <h3>🎯 Use Low Temperature</h3>
243 <p>Keep temperature at 0.1-0.3 for classification and analysis tasks for consistent results.</p>
244 </div>
245 <div class="tip-card">
246 <h3>📊 Structured Output</h3>
247 <p>Use JSON mode for reliable, parseable results that integrate easily with databases.</p>
248 </div>
249 <div class="tip-card">
250 <h3>✅ Validate Results</h3>
251 <p>Test with known examples, implement confidence thresholds, and monitor accuracy.</p>
252 </div>
253 <div class="tip-card">
254 <h3>⚡ Batch Process</h3>
255 <p>Process multiple items together for better efficiency and reduced API calls.</p>
256 </div>
257 <div class="tip-card">
258 <h3>🔍 Context Matters</h3>
259 <p>Provide domain context and clear instructions for better analysis accuracy.</p>
260 </div>
261 <div class="tip-card">
262 <h3>📈 Monitor Performance</h3>
263 <p>Track accuracy over time and collect feedback to improve your NLP systems.</p>
264 </div>
265 </div>
266 </section>
267
268 <!-- Processing Stats -->
269 <section class="card">
270 <h2>📊 Analysis Statistics (Demo)</h2>
271 <div class="stats-grid">
272 <div class="stat-card">
273 <div class="stat-number" id="total-analyses">0</div>
274 <div class="stat-label">Total Analyses</div>
275 </div>
276 <div class="stat-card">
277 <div class="stat-number" id="avg-confidence">--</div>
278 <div class="stat-label">Avg Confidence</div>
279 </div>
280 <div class="stat-card">
281 <div class="stat-number" id="processing-time">--</div>
282 <div class="stat-label">Avg Time (ms)</div>
283 </div>
284 </div>
285 </section>
286 </div>
287</body>
288</html>This comprehensive NLP Analysis Suite demonstrates all key concepts from Lesson 6:
🎯 Complete Coverage of NLP Tasks:
1. Sentiment Analysis:
2. Named Entity Recognition:
3. Text Classification:
4. Text Summarization:
5. Language Detection:
Educational Features:
Interactive Elements:
Visual Feedback:
Professional Features:
Production Patterns:
Learning Outcomes:
This demo serves as both a learning tool and a practical reference for implementing professional NLP features in applications.
Excellent work mastering text analysis and NLP tasks! You now understand sentiment analysis, entity extraction, classification, summarization, and language detection. In our next lesson, "Embeddings and Semantic Search," you'll learn about vector embeddings, how to build semantic search systems, create recommendation engines, and implement similarity-based features. Get ready to understand the mathematical foundation powering modern AI search!
Your progress is saved in this browser, on this device only.