This commit is contained in:
2026-02-06 10:12:24 +03:00
parent 801844807e
commit 834f21bb28
12 changed files with 1438 additions and 1181 deletions

View File

@@ -2,21 +2,6 @@
import sqlite3
import random
from datetime import datetime
from textblob import TextBlob # Simple NLP library
def analyze_joke_sentiment(joke_text):
"""Use AI to analyze the sentiment of a joke"""
analysis = TextBlob(joke_text)
polarity = analysis.sentiment.polarity
if polarity > 0.1:
label = "😊 Positive"
elif polarity < -0.1:
label = "😒 Negative"
else:
label = "😐 Neutral"
return polarity, label
def get_user_sentiment_for_joke(db, joke_id):
"""Get the average user sentiment for a specific joke"""
@@ -37,7 +22,7 @@ def get_user_sentiment_for_joke(db, joke_id):
''', (joke_id,))
result = cursor.fetchone()
avg_sentiment, total_votes = result
avg_sentiment, total_votes = result if result else ('😐 Neutral', 0)
return avg_sentiment, total_votes
def add_user_sentiment(db, joke_id, user_choice):
@@ -58,33 +43,29 @@ def main():
while True:
print("\n" + "="*30)
print("🤖 AI-ENHANCED JOKE BOT 🤖")
print("🤖 JOKE BOT 🤖")
print("="*30)
print("1. Get random joke")
print("2. Add new joke")
print("3. Analyze joke sentiment")
print("4. Get joke by mood")
print("5. View all jokes with sentiment")
print("6. Quit")
print("3. Quit")
choice = input("\nYour choice: ").strip()
if choice == "1":
# Get random joke with sentiment info
# Get random approved joke
cursor = db.execute('''
SELECT id, joke, contributor, published, sentiment_label
SELECT id, joke, contributor
FROM jokes
WHERE approved = 1
ORDER BY RANDOM()
LIMIT 1
''')
joke_data = cursor.fetchone()
if joke_data:
joke_id, joke, contributor, published, sentiment = joke_data
joke_id, joke, contributor = joke_data
print(f"\n🤣 {joke}")
print(f" 👤 Contributor: {contributor}")
print(f" 📅 Published: {published}")
print(f" 🧠 AI Mood Analysis: {sentiment}")
# Get and display user sentiment stats
avg_sentiment, total_votes = get_user_sentiment_for_joke(db, joke_id)
@@ -94,20 +75,14 @@ def main():
# Ask user for their sentiment
print(f"\n🎯 Rate this joke: 👍 (U)p, 👎 (D)own, or (N)eutral?")
user_input = input("Your choice (u/d/n): ").strip().lower()
if user_input in ['u', 'up']:
user_choice = 'up'
elif user_input in ['d', 'down']:
user_choice = 'down'
else:
user_choice = 'neutral'
user_choice = 'up' if user_input in ['u', 'up'] else 'down' if user_input in ['d', 'down'] else 'neutral'
if add_user_sentiment(db, joke_id, user_choice):
print(f"✅ Your rating ({'👍 Up' if user_choice == 'up' else '👎 Down' if user_choice == 'down' else '😐 Neutral'}) recorded!")
else:
print("❌ Could not save your rating.")
else:
print("📭 No jokes in the database yet!")
print(" No approved jokes in the database yet!")
elif choice == "2":
new_joke = input("Enter your joke: ").strip()
@@ -117,172 +92,32 @@ def main():
name = input("Your name (or press Enter for 'Anonymous'): ").strip() or "Anonymous"
# AI Analysis
score, label = analyze_joke_sentiment(new_joke)
print(f"\n🤖 AI Analysis Results:")
print(f" Sentiment Score: {score:.2f}")
print(f" Mood Label: {label}")
# Get current date/time
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
cursor = db.cursor()
cursor.execute('''
INSERT INTO jokes (joke, contributor, published, sentiment_score, sentiment_label)
VALUES (?, ?, ?, ?, ?)
''', (new_joke, name, current_time, score, label))
INSERT INTO jokes (joke, contributor, created_date, approved)
VALUES (?, ?, ?, 0)
''', (new_joke, name, current_time))
# Get the ID of the newly inserted joke
new_joke_id = cursor.lastrowid
db.commit()
print("Joke saved with AI analysis!")
# Ask user for their sentiment on the new joke
print(f"\n🎯 Rate your own joke: 👍 (U)p, 👎 (D)own, or (N)eutral?")
user_input = input("Your choice (u/d/n): ").strip().lower()
if user_input in ['u', 'up']:
user_choice = 'up'
elif user_input in ['d', 'down']:
user_choice = 'down'
else:
user_choice = 'neutral'
if add_user_sentiment(db, new_joke_id, user_choice):
print(f"✅ Your rating ({'👍 Up' if user_choice == 'up' else '👎 Down' if user_choice == 'down' else '😐 Neutral'}) recorded!")
print("Submitted for approval!")
except Exception as e:
print(f"❌ Error saving joke: {e}")
elif choice == "3":
joke_text = input("Enter a joke to analyze: ").strip()
if joke_text:
score, label = analyze_joke_sentiment(joke_text)
print(f"\n📊 AI Analysis Results:")
print(f" Joke: '{joke_text}'")
print(f" Sentiment Score: {score:.2f}")
print(f" Mood Label: {label}")
# Interpretation
print(f"\n📈 Interpretation:")
if score > 0.5:
print(" Very positive joke! 😄")
elif score > 0.1:
print(" Positive joke! 😊")
elif score < -0.5:
print(" Very negative/sarcastic joke! 😠")
elif score < -0.1:
print(" Negative joke! 😒")
else:
print(" Neutral joke! 😐")
else:
print("❌ Please enter a joke to analyze.")
elif choice == "4":
print("\n🎭 Choose mood:")
print("1. 😊 Positive jokes")
print("2. 😒 Negative jokes")
print("3. 😐 Neutral jokes")
print("4. 😄 Very positive jokes (score > 0.5)")
print("5. 😠 Very negative jokes (score < -0.5)")
mood_choice = input("Your choice: ").strip()
mood_queries = {
"1": ("😊 Positive", "sentiment_label = '😊 Positive'"),
"2": ("😒 Negative", "sentiment_label = '😒 Negative'"),
"3": ("😐 Neutral", "sentiment_label = '😐 Neutral'"),
"4": ("😄 Very Positive", "sentiment_score > 0.5"),
"5": ("😠 Very Negative", "sentiment_score < -0.5")
}
if mood_choice in mood_queries:
mood_name, query = mood_queries[mood_choice]
cursor = db.execute(f'''
SELECT id, joke, contributor, sentiment_score
FROM jokes
WHERE {query}
ORDER BY RANDOM()
LIMIT 1
''')
joke_data = cursor.fetchone()
if joke_data:
joke_id, joke, contributor, score = joke_data
print(f"\n{mood_name} joke:")
print(f"🤣 {joke}")
print(f" 👤 Contributor: {contributor}")
print(f" 📊 Sentiment Score: {score:.2f}")
# Get and display user sentiment stats
avg_sentiment, total_votes = get_user_sentiment_for_joke(db, joke_id)
if total_votes > 0:
print(f" 👥 Community Rating: {avg_sentiment} ({total_votes} votes)")
# Ask user for their sentiment
print(f"\n🎯 Rate this joke: 👍 (U)p, 👎 (D)own, or (N)eutral?")
user_input = input("Your choice (u/d/n): ").strip().lower()
if user_input in ['u', 'up']:
user_choice = 'up'
elif user_input in ['d', 'down']:
user_choice = 'down'
else:
user_choice = 'neutral'
if add_user_sentiment(db, joke_id, user_choice):
print(f"✅ Your rating ({'👍 Up' if user_choice == 'up' else '👎 Down' if user_choice == 'down' else '😐 Neutral'}) recorded!")
else:
print(f"📭 No {mood_name.lower()} jokes yet!")
else:
print("❌ Invalid choice!")
elif choice == "5":
print("\n📋 ALL JOKES IN DATABASE:")
print("-" * 70)
cursor = db.execute('''
SELECT j.id, j.joke, j.contributor, j.sentiment_label, j.sentiment_score
FROM jokes j
ORDER BY j.id DESC
''')
jokes = cursor.fetchall()
if jokes:
for i, (joke_id, joke, contributor, label, score) in enumerate(jokes, 1):
print(f"\n{i}. {joke}")
print(f" 👤 {contributor} | AI: {label} | Score: {score:.2f}")
# Get and display user sentiment stats
avg_sentiment, total_votes = get_user_sentiment_for_joke(db, joke_id)
if total_votes > 0:
print(f" 👥 Community Rating: {avg_sentiment} ({total_votes} votes)")
print(f"\n📊 Total jokes: {len(jokes)}")
else:
print("📭 No jokes in the database yet!")
elif choice == "6":
print("\n👋 Goodbye! Thanks for using the AI Joke Bot!")
print("\n👋 Goodbye!")
break
else:
print("❌ Invalid choice. Please select 1-6.")
print("❌ Invalid choice. Please select 1-3.")
db.close()
if __name__ == "__main__":
# Check if textblob is installed
try:
import textblob
main()
except ImportError:
print("❌ ERROR: textblob library is not installed!")
print("\n📦 Please install it using:")
print(" pip install textblob")
print(" python -m textblob.download_corpora")
print("\nThen run this script again.")
main()