Random Quote Generator

import json

import random

import os

from datetime import datetime

from pathlib import Path

from collections import defaultdict


try:

    import requests

    REQUESTS_OK = True

except ImportError:

    REQUESTS_OK = False


# ============================================================

# CONFIGURATION

# ============================================================


QUOTES_FILE    = "quotes.json"

FAVORITES_FILE = "favorite_quotes.json"

HISTORY_FILE   = "quote_history.json"


# Free API — no key needed

QUOTE_API_URL  = "https://api.quotable.io/random"

QUOTES_BY_TAG  = "https://api.quotable.io/quotes?tags={tag}&limit=20"


# ============================================================

# BUILT-IN QUOTE DATABASE (works offline)

# ============================================================


BUILTIN_QUOTES = [

    # Motivation

    {"text": "The only way to do great work is to love what you do.", "author": "Steve Jobs", "category": "motivation"},

    {"text": "It does not matter how slowly you go as long as you do not stop.", "author": "Confucius", "category": "motivation"},

    {"text": "Success is not final, failure is not fatal: it is the courage to continue that counts.", "author": "Winston Churchill", "category": "motivation"},

    {"text": "Believe you can and you're halfway there.", "author": "Theodore Roosevelt", "category": "motivation"},

    {"text": "The secret of getting ahead is getting started.", "author": "Mark Twain", "category": "motivation"},

    {"text": "Don't watch the clock; do what it does. Keep going.", "author": "Sam Levenson", "category": "motivation"},

    {"text": "You are never too old to set another goal or to dream a new dream.", "author": "C.S. Lewis", "category": "motivation"},

    {"text": "The future belongs to those who believe in the beauty of their dreams.", "author": "Eleanor Roosevelt", "category": "motivation"},


    # Wisdom

    {"text": "In the middle of every difficulty lies opportunity.", "author": "Albert Einstein", "category": "wisdom"},

    {"text": "Life is what happens when you're busy making other plans.", "author": "John Lennon", "category": "wisdom"},

    {"text": "The only true wisdom is in knowing you know nothing.", "author": "Socrates", "category": "wisdom"},

    {"text": "Yesterday is history, tomorrow is a mystery, today is a gift of God.", "author": "Bill Keane", "category": "wisdom"},

    {"text": "We do not remember days, we remember moments.", "author": "Cesare Pavese", "category": "wisdom"},

    {"text": "The unexamined life is not worth living.", "author": "Socrates", "category": "wisdom"},

    {"text": "He who knows others is wise; he who knows himself is enlightened.", "author": "Lao Tzu", "category": "wisdom"},

    {"text": "The journey of a thousand miles begins with one step.", "author": "Lao Tzu", "category": "wisdom"},


    # Success

    {"text": "Success usually comes to those who are too busy to be looking for it.", "author": "Henry David Thoreau", "category": "success"},

    {"text": "I find that the harder I work, the more luck I seem to have.", "author": "Thomas Jefferson", "category": "success"},

    {"text": "Don't be afraid to give up the good to go for the great.", "author": "John D. Rockefeller", "category": "success"},

    {"text": "I have not failed. I've just found 10,000 ways that won't work.", "author": "Thomas Edison", "category": "success"},

    {"text": "The road to success and the road to failure are almost exactly the same.", "author": "Colin R. Davis", "category": "success"},

    {"text": "Success is walking from failure to failure with no loss of enthusiasm.", "author": "Winston Churchill", "category": "success"},


    # Happiness

    {"text": "Happiness is not something ready-made. It comes from your own actions.", "author": "Dalai Lama", "category": "happiness"},

    {"text": "For every minute you are angry you lose sixty seconds of happiness.", "author": "Ralph Waldo Emerson", "category": "happiness"},

    {"text": "The most wasted of days is one without laughter.", "author": "E.E. Cummings", "category": "happiness"},

    {"text": "Count your age by friends, not years. Count your life by smiles, not tears.", "author": "John Lennon", "category": "happiness"},

    {"text": "Happiness depends upon ourselves.", "author": "Aristotle", "category": "happiness"},


    # Technology

    {"text": "Any sufficiently advanced technology is indistinguishable from magic.", "author": "Arthur C. Clarke", "category": "technology"},

    {"text": "It's not a faith in technology. It's faith in people.", "author": "Steve Jobs", "category": "technology"},

    {"text": "The science of today is the technology of tomorrow.", "author": "Edward Teller", "category": "technology"},

    {"text": "Technology is best when it brings people together.", "author": "Matt Mullenweg", "category": "technology"},

    {"text": "The real danger is not that computers will begin to think like men, but that men will begin to think like computers.", "author": "Sydney J. Harris", "category": "technology"},


    # Programming

    {"text": "First, solve the problem. Then, write the code.", "author": "John Johnson", "category": "programming"},

    {"text": "Programs must be written for people to read, and only incidentally for machines to execute.", "author": "Harold Abelson", "category": "programming"},

    {"text": "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.", "author": "Martin Fowler", "category": "programming"},

    {"text": "The most important property of a program is whether it accomplishes the intention of its user.", "author": "C.A.R. Hoare", "category": "programming"},

    {"text": "Debugging is twice as hard as writing the code in the first place.", "author": "Brian Kernighan", "category": "programming"},

    {"text": "Talk is cheap. Show me the code.", "author": "Linus Torvalds", "category": "programming"},

    {"text": "Clean code always looks like it was written by someone who cares.", "author": "Robert C. Martin", "category": "programming"},

    {"text": "Simplicity is the soul of efficiency.", "author": "Austin Freeman", "category": "programming"},


    # Life

    {"text": "Life is short, and it's up to you to make it sweet.", "author": "Sarah Louise Delany", "category": "life"},

    {"text": "In three words I can sum up everything I've learned about life: it goes on.", "author": "Robert Frost", "category": "life"},

    {"text": "To live is the rarest thing in the world. Most people exist, that is all.", "author": "Oscar Wilde", "category": "life"},

    {"text": "Life is really simple, but we insist on making it complicated.", "author": "Confucius", "category": "life"},

    {"text": "The purpose of life is not to be happy but to be useful.", "author": "Ralph Waldo Emerson", "category": "life"},


    # Courage

    {"text": "You gain strength, courage, and confidence by every experience in which you really stop to look fear in the face.", "author": "Eleanor Roosevelt", "category": "courage"},

    {"text": "Courage is not the absence of fear, but the triumph over it.", "author": "Nelson Mandela", "category": "courage"},

    {"text": "It takes courage to grow up and become who you really are.", "author": "E.E. Cummings", "category": "courage"},

    {"text": "Fortune favors the brave.", "author": "Virgil", "category": "courage"},


    # Learning

    {"text": "Live as if you were to die tomorrow. Learn as if you were to live forever.", "author": "Mahatma Gandhi", "category": "learning"},

    {"text": "An investment in knowledge pays the best interest.", "author": "Benjamin Franklin", "category": "learning"},

    {"text": "Education is the most powerful weapon which you can use to change the world.", "author": "Nelson Mandela", "category": "learning"},

    {"text": "The beautiful thing about learning is that no one can take it away from you.", "author": "B.B. King", "category": "learning"},

    {"text": "Tell me and I forget. Teach me and I remember. Involve me and I learn.", "author": "Benjamin Franklin", "category": "learning"},

]


# ============================================================

# LOAD & SAVE

# ============================================================


def load_quotes():

    if Path(QUOTES_FILE).exists():

        try:

            with open(QUOTES_FILE, "r", encoding="utf-8") as f:

                return json.load(f)

        except:

            pass

    # First run — save built-in quotes

    save_quotes(BUILTIN_QUOTES)

    return BUILTIN_QUOTES



def save_quotes(quotes):

    with open(QUOTES_FILE, "w", encoding="utf-8") as f:

        json.dump(quotes, f, indent=2, ensure_ascii=False)



def load_favorites():

    if Path(FAVORITES_FILE).exists():

        try:

            with open(FAVORITES_FILE, "r", encoding="utf-8") as f:

                return json.load(f)

        except:

            pass

    return []



def save_favorites(favs):

    with open(FAVORITES_FILE, "w", encoding="utf-8") as f:

        json.dump(favs, f, indent=2, ensure_ascii=False)



def load_history():

    if Path(HISTORY_FILE).exists():

        try:

            with open(HISTORY_FILE, "r", encoding="utf-8") as f:

                return json.load(f)

        except:

            pass

    return []



def save_to_history(quote):

    history = load_history()

    history.append({

        "text":     quote["text"],

        "author":   quote["author"],

        "category": quote.get("category", ""),

        "shown_at": datetime.now().strftime("%d-%m-%Y %H:%M:%S"),

    })

    history = history[-100:]

    with open(HISTORY_FILE, "w", encoding="utf-8") as f:

        json.dump(history, f, indent=2, ensure_ascii=False)



# ============================================================

# DISPLAY QUOTE

# ============================================================


def display_quote(quote, show_box=True):

    text     = quote.get("text", "")

    author   = quote.get("author", "Unknown")

    category = quote.get("category", "")


    if show_box:

        width = min(max(len(text) + 6, 50), 65)

        print("\n" + "─" * width)


        # Word-wrap text

        words   = text.split()

        lines   = []

        current = ""

        for word in words:

            if len(current) + len(word) + 1 <= width - 6:

                current = current + " " + word if current else word

            else:

                lines.append(current)

                current = word

        if current:

            lines.append(current)


        for line in lines:

            print(f"  {line}")


        print(f"\n  — {author}")

        if category:

            print(f"  [{category}]")

        print("─" * width)

    else:

        print(f"\n  \"{text}\"")

        print(f"  — {author}")

        if category:

            print(f"  [{category}]")



# ============================================================

# FETCH FROM API

# ============================================================


def fetch_online_quote(tag=None):

    if not REQUESTS_OK:

        return None

    try:

        url  = QUOTES_BY_TAG.format(tag=tag) if tag else QUOTE_API_URL

        resp = requests.get(url, timeout=8)

        resp.raise_for_status()

        data = resp.json()


        # quotable.io returns either a single object or {results: [...]}

        if "results" in data:

            items = data["results"]

            if not items:

                return None

            item = random.choice(items)

        else:

            item = data


        return {

            "text":     item.get("content", ""),

            "author":   item.get("author", "Unknown"),

            "category": tag or "online",

        }

    except Exception as e:

        return None



# ============================================================

# GET RANDOM QUOTE

# ============================================================


def get_random_quote(quotes, category=None):

    pool = quotes

    if category:

        pool = [q for q in quotes if q.get("category", "").lower() == category.lower()]

        if not pool:

            print(f"  No quotes in category '{category}'. Showing random.")

            pool = quotes

    return random.choice(pool) if pool else None



# ============================================================

# QUOTE OF THE DAY

# ============================================================


def quote_of_the_day(quotes):

    """Deterministic quote based on today's date — same quote all day."""

    today_num = int(datetime.now().strftime("%Y%j"))

    idx       = today_num % len(quotes)

    quote     = quotes[idx]


    print("\n" + "="*55)

    print(f"  QUOTE OF THE DAY  —  {datetime.now().strftime('%d %B %Y')}")

    print("="*55)

    display_quote(quote)



# ============================================================

# ADD CUSTOM QUOTE

# ============================================================


def add_quote(quotes):

    print("\n  ADD YOUR OWN QUOTE")

    print("  " + "-"*40)


    text   = input("  Quote text  : ").strip()

    author = input("  Author      : ").strip() or "Unknown"


    # Show categories

    cats = sorted(set(q.get("category", "") for q in quotes if q.get("category")))

    print(f"  Categories  : {', '.join(cats)}")

    category = input("  Category    : ").strip().lower() or "general"


    if not text:

        print("  Quote text is required.")

        return quotes


    quote = {

        "text":     text,

        "author":   author,

        "category": category,

        "custom":   True,

        "added_at": datetime.now().strftime("%d-%m-%Y %H:%M"),

    }

    quotes.append(quote)

    save_quotes(quotes)

    print(f"\n  Quote added! Total quotes: {len(quotes)}")

    return quotes



# ============================================================

# SEARCH QUOTES

# ============================================================


def search_quotes(quotes, keyword):

    keyword = keyword.lower()

    results = [

        q for q in quotes

        if keyword in q["text"].lower()

        or keyword in q["author"].lower()

        or keyword in q.get("category", "").lower()

    ]


    if not results:

        print(f"\n  No quotes found for: '{keyword}'")

        return


    print(f"\n  Found {len(results)} quote(s) for '{keyword}':\n")

    for i, q in enumerate(results[:10], 1):

        print(f"  [{i}] \"{q['text'][:70]}{'...' if len(q['text']) > 70 else ''}\"")

        print(f"       — {q['author']}  [{q.get('category', '')}]\n")


    if len(results) > 10:

        print(f"  ... and {len(results) - 10} more.")



# ============================================================

# FAVORITES

# ============================================================


def add_to_favorites(quote):

    favs = load_favorites()

    if any(f["text"] == quote["text"] for f in favs):

        print("  Already in favorites.")

        return

    favs.append({

        "text":     quote["text"],

        "author":   quote["author"],

        "category": quote.get("category", ""),

        "saved_at": datetime.now().strftime("%d-%m-%Y %H:%M"),

    })

    save_favorites(favs)

    print("  Added to favorites!")



def view_favorites():

    favs = load_favorites()

    if not favs:

        print("\n  No favorites yet.")

        return


    print("\n" + "="*55)

    print(f"  FAVORITE QUOTES  ({len(favs)})")

    print("="*55)

    for i, q in enumerate(favs, 1):

        print(f"\n  [{i}]")

        display_quote(q, show_box=False)


    print("="*55)



def remove_from_favorites():

    favs = load_favorites()

    if not favs:

        print("\n  No favorites to remove.")

        return


    view_favorites()

    try:

        idx = int(input("\n  Enter number to remove: ").strip()) - 1

        if 0 <= idx < len(favs):

            removed = favs.pop(idx)

            save_favorites(favs)

            print(f"  Removed: \"{removed['text'][:50]}...\"")

        else:

            print("  Invalid number.")

    except ValueError:

        print("  Invalid input.")



# ============================================================

# CATEGORY STATS

# ============================================================


def show_stats(quotes):

    total      = len(quotes)

    categories = defaultdict(int)

    authors    = defaultdict(int)

    custom     = sum(1 for q in quotes if q.get("custom"))


    for q in quotes:

        categories[q.get("category", "uncategorized")] += 1

        authors[q.get("author", "Unknown")] += 1


    print("\n" + "="*50)

    print(f"  QUOTE LIBRARY STATS")

    print("="*50)

    print(f"  Total quotes   : {total}")

    print(f"  Custom quotes  : {custom}")

    print(f"  Favorites      : {len(load_favorites())}")

    print(f"  Categories     : {len(categories)}")

    print(f"  Authors        : {len(authors)}")


    print(f"\n  BY CATEGORY:")

    max_count = max(categories.values()) if categories else 1

    for cat, count in sorted(categories.items(), key=lambda x: -x[1]):

        bar = "█" * int((count / max_count) * 20)

        print(f"  {cat:<18} {count:>4}  {bar}")


    print(f"\n  TOP 5 AUTHORS:")

    for author, count in sorted(authors.items(), key=lambda x: -x[1])[:5]:

        print(f"  {author:<30} {count} quote(s)")


    print("="*50)



# ============================================================

# QUOTE SLIDESHOW

# ============================================================


def slideshow(quotes, category=None, count=5):

    """Display N quotes one by one."""

    pool = quotes

    if category:

        pool = [q for q in quotes

                if q.get("category", "").lower() == category.lower()]

        if not pool:

            pool = quotes


    sample = random.sample(pool, min(count, len(pool)))


    print(f"\n  SLIDESHOW  —  {len(sample)} quotes")

    print("  Press Enter for next, 'f' to favorite, 'q' to quit\n")


    for i, quote in enumerate(sample, 1):

        print(f"\n  Quote {i} of {len(sample)}")

        display_quote(quote)

        save_to_history(quote)


        action = input("\n  [Enter=next | f=favorite | q=quit]: ").strip().lower()

        if action == "f":

            add_to_favorites(quote)

        elif action == "q":

            break



# ============================================================

# VIEW HISTORY

# ============================================================


def view_history():

    history = load_history()

    if not history:

        print("\n  No quote history yet.")

        return


    print("\n" + "="*60)

    print(f"  RECENTLY VIEWED QUOTES  (last {min(len(history), 10)})")

    print("="*60)


    for h in reversed(history[-10:]):

        print(f"\n  {h['shown_at']}  [{h.get('category', '')}]")

        print(f"  \"{h['text'][:70]}{'...' if len(h['text']) > 70 else ''}\"")

        print(f"  — {h['author']}")


    print("="*60)



# ============================================================

# MAIN MENU

# ============================================================


def print_menu(quotes):

    cats  = sorted(set(q.get("category", "") for q in quotes if q.get("category")))

    total = len(quotes)

    favs  = len(load_favorites())

    print("\n" + "-"*50)

    print(f"  RANDOM QUOTE GENERATOR  [{total} quotes | ★{favs} favs]")

    print("-"*50)

    print("  1.  Random quote")

    print("  2.  Quote by category")

    print("  3.  Quote of the day")

    print("  4.  Quote slideshow")

    print("  5.  Fetch online quote (API)")

    print("  6.  Search quotes")

    print("  7.  Add your own quote")

    print("  8.  View favorites")

    print("  9.  Remove from favorites")

    print("  10. View history")

    print("  11. Library stats")

    print("  0.  Exit")

    print(f"\n  Categories: {', '.join(cats)}")

    print("-"*50)



def main():

    print("\n" + "="*55)

    print("     RANDOM QUOTE GENERATOR")

    print("="*55)


    quotes = load_quotes()

    print(f"\n  Loaded {len(quotes)} quotes from library.")

    print("  Works offline with built-in quotes.")

    if REQUESTS_OK:

        print("  Online API enabled (quotable.io).")


    while True:

        print_menu(quotes)

        choice = input("  > ").strip()


        if choice == "1":

            quote = get_random_quote(quotes)

            if quote:

                display_quote(quote)

                save_to_history(quote)

                fav = input("\n  Add to favorites? (y/n): ").strip().lower()

                if fav == "y":

                    add_to_favorites(quote)


        elif choice == "2":

            cats = sorted(set(q.get("category", "") for q in quotes if q.get("category")))

            print(f"\n  Available: {', '.join(cats)}")

            cat = input("  Category: ").strip()

            quote = get_random_quote(quotes, cat)

            if quote:

                display_quote(quote)

                save_to_history(quote)

                fav = input("\n  Add to favorites? (y/n): ").strip().lower()

                if fav == "y":

                    add_to_favorites(quote)


        elif choice == "3":

            quote_of_the_day(quotes)


        elif choice == "4":

            cats = sorted(set(q.get("category", "") for q in quotes if q.get("category")))

            print(f"\n  Categories: {', '.join(cats)}")

            cat = input("  Category (Enter=all): ").strip() or None

            try:

                n = int(input("  Number of quotes (default 5): ").strip() or 5)

            except ValueError:

                n = 5

            slideshow(quotes, cat, n)


        elif choice == "5":

            if not REQUESTS_OK:

                print("\n  requests not installed: pip install requests")

            else:

                print("\n  Popular tags: inspirational, life, humor, love, technology")

                tag   = input("  Tag (Enter=random): ").strip() or None

                print("  Fetching...")

                quote = fetch_online_quote(tag)

                if quote:

                    display_quote(quote)

                    save_to_history(quote)

                    # Offer to save to local library

                    save = input("\n  Save to local library? (y/n): ").strip().lower()

                    if save == "y":

                        quotes.append(quote)

                        save_quotes(quotes)

                        print("  Saved!")

                    fav = input("  Add to favorites? (y/n): ").strip().lower()

                    if fav == "y":

                        add_to_favorites(quote)

                else:

                    print("  Could not fetch online quote. Check internet connection.")


        elif choice == "6":

            kw = input("\n  Search keyword: ").strip()

            if kw:

                search_quotes(quotes, kw)


        elif choice == "7":

            quotes = add_quote(quotes)


        elif choice == "8":

            view_favorites()


        elif choice == "9":

            remove_from_favorites()


        elif choice == "10":

            view_history()


        elif choice == "11":

            show_stats(quotes)


        elif choice == "0":

            print("\n  Goodbye! Stay inspired!\n")

            break


        else:

            print("  Invalid choice.")



# ============================================================

# RUN

# ============================================================


if __name__ == "__main__":

    main()

No comments: