help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
nlp-text-analysis-bot
RSK World
nlp-text-analysis-bot
NLP Text Analysis Bot - Python + NLP + Flask + Machine Learning + Text Analysis + AI
nlp-text-analysis-bot
  • __pycache__
  • static
  • templates
  • .gitignore90 B
  • LICENSE1.1 KB
  • README.md1.1 KB
  • RELEASE_NOTES.md1.1 KB
  • app.py2.3 KB
  • bot_logic.py4.6 KB
  • models.py2.7 KB
  • requirements.txt194 B
sentiment_analyzer.pyapp.pybot_logic.py
app.py
Raw Download
Find: Go to:
"""
Project: Customer Service Bot
Author: RSK World
Website: https://rskworld.in
Contact: info@rskworld.com, support@rskworld.com
Phone: +91 93305 39277
Year: 2026
"""

from flask import Flask, render_template, request, jsonify, Response
from bot_logic import get_response, analyze_sentiment
from models import init_db, create_ticket, get_all_tickets, update_ticket_status, get_ticket_stats
import io
import csv

app = Flask(__name__)

# Initialize Database
init_db(app)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/admin')
def admin():
    """
    Admin Dashboard to view tickets and stats
    """
    tickets = get_all_tickets()
    stats = get_ticket_stats()
    return render_template('admin.html', tickets=tickets, stats=stats)

@app.route('/admin/export')
def export_tickets():
    """
    Export all tickets to CSV
    """
    tickets = get_all_tickets()
    
    # Create CSV in memory
    output = io.StringIO()
    writer = csv.writer(output)
    
    # Header
    writer.writerow(['ID', 'Issue', 'Contact', 'Priority', 'Status', 'Sentiment Score', 'Created At'])
    
    # Data
    for t in tickets:
        writer.writerow([t['id'], t['issue'], t['contact'], t['priority'], t['status'], t['sentiment_score'], t['created_at']])
        
    output.seek(0)
    
    return Response(
        output,
        mimetype="text/csv",
        headers={"Content-Disposition": "attachment;filename=tickets_export.csv"}
    )

@app.route('/api/chat', methods=['POST'])
def chat():
    user_message = request.json.get('message')
    response_data = get_response(user_message)
    return jsonify(response_data)

@app.route('/api/ticket', methods=['POST'])
def ticket():
    data = request.json
    issue = data.get('issue')
    contact = data.get('contact')
    
    # Analyze sentiment
    score, priority = analyze_sentiment(issue)
    
    ticket_id = create_ticket(issue, contact, priority, score)
    
    return jsonify({
        'status': 'success', 
        'ticket_id': ticket_id,
        'priority': priority
    })

@app.route('/api/ticket/<int:ticket_id>/close', methods=['POST'])
def close_ticket(ticket_id):
    update_ticket_status(ticket_id, 'Closed')
    return jsonify({'status': 'success'})

if __name__ == '__main__':
    app.run(debug=True, port=5000)
90 lines•2.3 KB
python
bot_logic.py
Raw Download
Find: Go to:
"""
Project: Customer Service Bot
Author: RSK World
Website: https://rskworld.in
Contact: info@rskworld.com, support@rskworld.com
Phone: +91 93305 39277
Year: 2026
"""

from difflib import get_close_matches

# Extended Knowledge Base
FAQ_KB = {
    "hours": "We are open 24/7 for your convenience!",
    "location": "We are a digital-first company, operating globally.",
    "refund": "Refunds are processed within 3-5 business days. Please provide your Order ID.",
    "pricing": "Our basic plan starts at $0. Free tier available. Premium plans start at $10/mo.",
    "hiring": "We are always looking for talent! Check our careers page.",
    "contact": "You can reach us at info@rskworld.com or +91 93305 39277.",
    "hello": "Hello! Welcome to our Customer Service. How can I help you today?",
    "hi": "Hi there! Need assistance?",
    "bye": "Goodbye! Have a great day ahead.",
    "password": "To reset your password, click 'Forgot Password' on the login page.",
    "shipping": "Shipping usually takes 2-4 business days within the country.",
    "payment": "We accept Visa, Mastercard, PayPal, and Crypto.",
    "cancel": "You can cancel your subscription anytime from your settings.",
    "agent": "I can connect you to a human agent if you raise a ticket.",
    "status": "You can check the status of your ticket on the 'My Tickets' page.",
    "features": "Our bot supports FAQ handling, ticket management, and sentiment analysis."
}

# Negative words for basic sentiment analysis
NEGATIVE_WORDS = ['angry', 'bad', 'terrible', 'worst', 'fail', 'broken', 'scam', 'late', 'hate', 'stupid', 'useless', 'waiting', 'ridiculous']
URGENT_WORDS = ['manager', 'supervisor', 'emergency', 'urgent', 'legal', 'sue']

def analyze_sentiment(text):
    """
    Basic sentiment analysis to detect frustration and urgency.
    Returns: (score, priority_label)
    """
    text = text.lower()
    score = 0
    
    # Check for urgency keywords
    for word in URGENT_WORDS:
        if word in text:
            return 10, 'High' # Immediate High Priority

    for word in NEGATIVE_WORDS:
        if word in text:
            score += 1
            
    if score >= 2:
        return score, 'High'
    elif score == 1:
        return score, 'Medium'
    else:
        return score, 'Normal'

def get_response(message):
    """
    Determine the bot response using Fuzzy Matching, Intent Detection, and Sentiment Adaptation.
    Project: Customer Service Bot
    Author: RSK World
    Year: 2026
    """
    msg = message.lower().strip()
    sentiment_score, priority = analyze_sentiment(msg)
    
    # Adaptive Tone: Apologize if user is upset
    prefix = ""
    if sentiment_score > 0:
        prefix = "I understand you are upset. I apologize for the inconvenience. "

    # 1. Check for immediate escalation triggers
    if priority == 'High' and "ticket" not in msg:
        return {
            "text": f"{prefix}It sounds like this is urgent. I strongly recommend raising a high-priority ticket immediately.",
            "type": "option",
            "options": ["Yes, raise a ticket"]
        }

    # 2. Advanced Fuzzy Matching for FAQ
    keys = list(FAQ_KB.keys())
    msg_words = msg.split()
    best_match = None
    
    # Check words
    for word in msg_words:
        matches = get_close_matches(word, keys, n=1, cutoff=0.7)
        if matches:
            best_match = matches[0]
            break
            
    # Direct search
    if not best_match:
        for key in keys:
            if key in msg:
                best_match = key
                break
                
    if best_match:
        return {
            "text": f"{prefix}{FAQ_KB[best_match]}",
            "type": "text"
        }
    
    # 3. Intent Detection for Ticket/Support
    if "ticket" in msg or "issue" in msg or "problem" in msg or "help" in msg or "human" in msg:
        response_text = "It seems you have an issue."
        if priority == 'High':
            response_text = f"{prefix}Let's prioritize getting you help. Would you like to raise a high-priority ticket?"
        else:
            response_text = f"{prefix}Would you like to raise a support ticket so our team can help?"
            
        return {
            "text": response_text,
            "type": "option",
            "options": ["Yes, raise a ticket"]
        }
        
    # 4. Smart Fallback with Suggestion
    return {
        "text": f"{prefix}I'm not quite sure about that. I can help with FAQs (hours, refunds, pricing) or you can say 'help' to talk to support.",
        "type": "text"
    }
127 lines•4.6 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer