JustToThePoint English Website Version
JustToThePoint en español

Building a Lightning-Fast AI-CLI Toolkit in Python

If you’re going through hell, keep on going, Winston Churchill

image info

While graphical user interfaces (GUIs) are common and dominate mainstream apps, command-line interfaces (CLIs) remain a very efficient way to interact with computers, especially for tasks like automation, AI, system administration, and headless server tasks.

When you add AI capabilities —like Ollama’s local LLM engine— having a robust set of UI helpers makes a world of difference. In this article, we’ll walk through a Python module that provides:

nvim util.py
from quote import quote # Importing the quote function from the quote module
# quote is a python wrapper for the Goodreads Quote API, powered by gazpacho.
import random
def select_quote():
    """Print a list of quotes from the quote library.

    Returns:
        None or a list of quotes
    """
    topics = ["life", "love", "inspiration", "wisdom", "humor", "motivation", "maths",
              "coding", "linux", "software", "programming"]  # List of topics for quotes
    topic = random.choice(topics)  # Randomly select a topic from the list
    # Display a message indicating that a quote is being fetched
    display_text_color(f"Fetching a quote on {topic}...", Fore.BLACK)
    # Fetch quotes from the quote library for the selected topic
    myquotes = quote(topic, limit=5)
    # Display the quotes from the library
    for entry in myquotes:
        # Display the quote, author, and book
        display_text_color(f"{entry['quote']}\n -- {entry['author']} ({entry['book']})\n", Fore.CYAN)

    # Return the list of quotes
    return myquotes

def news():
    """Fetch and display the latest news headlines.

    Returns:
        None
    """
    # Load environment variables from .env file
    # Get the directory of the current script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # Construct the path to the .env file
    dotenv_path = os.path.join(script_dir, '.env')
    # Load the environment variables from the .env file
    load_dotenv(dotenv_path, override=True)
    # Various free news RSS feeds
    # Fetch the RSS_FEED_URLS variable from the environment
    raw = os.getenv("RSS_FEED_URLS", "")
    if not raw:  # Check if the variable is empty
        # Display a message indicating that no RSS feeds are found
        display_alarm_color("No RSS feeds found. Please set the RSS_FEED_URLS environment variable.", Fore.RED)
        return None  # Exit if no RSS feeds are found
    rss_feeds = raw.split()  # Split the RSS feed URLs into a list
    if not rss_feeds:  # Check if the list is empty
        display_alarm_color("No RSS feeds provided.", Fore.RED)
        return None  # Exit if no RSS feeds are provided
    if len(rss_feeds) < 1:  # Check the length of the list
        display_alarm_color("At least one RSS feed is required to fetch news.", Fore.RED)
        return None  # Exit if no RSS feeds are present
    # Display the RSS feeds being used for content expansion
    display_text_color(f"RSS feeds: {', '.join(rss_feeds)}", Fore.BLACK)

    display_text_color("Fetching news from RSS feeds...", Fore.BLACK)
    # Loop or iterate through the list of RSS feeds
    for feed_url in rss_feeds:
        try:
            # Parse the RSS feed into a structured format
            feed = feedparser.parse(feed_url)
            for entry in feed.entries: # Loop through each entry in the feed
                # Display the title and link of each news entry in yellow
                display_text_color(f"{entry.title} - {entry.link}", Fore.YELLOW)
                # Display the summary of each news entry
                # Show a truncated summary if it's longer than 200 characters
                display_text_color(f"{entry.summary[:200]}...\n", Fore.BLUE)
        except:  # Catch any exceptions that might occur during feed fetching
            display_alarm_color(f"Failed to fetch {feed}")

def stocks():
    """Display today's closing prices for a list of major US stocks.

    The list of stocks is hardcoded but can be easily customized.
    """
    TICKERS = ["AAPL", "MSFT", "GOOGL", "AMZN",  # List of major US stock tickers
               "TSLA", "BRK-B", "NVDA", "META", "JPM", "V"]
    display_text_color("Fetching today's stock prices...",
                       Fore.BLACK)  # Indicate fetching process

    # Loop or iterate through the list of stock tickers
    for ticker in TICKERS:
        # Fetch the stock data using yfinance
        # yfinance is an open-source tool that uses Yahoo's publicly available APIs.
        # It is intended exclusively for research and educational purposes.
        stock = yf.Ticker(ticker) # Create a Ticker object for the stock
        # Get the historical data for the stock
        # Here we use '1d' to get the latest day's data
        data = stock.history(period="1d")
        if not data.empty: # Check if the data is not empty
            # Get the closing price from the data
            price = data["Close"].iloc[0]
            # Display the ticker and closing price
            display_text_color(f"{ticker}: ${price:.2f}")
        else:  # If the data is empty
            # Indicate no data available
            display_text_color(f"{ticker}: No data")

def check_website_status(url : str, timeout : int = 10):
    """
    Check if a website is running and accessible.

    Args:
        url (str): The website URL to check
        timeout (int): Request timeout in seconds

    Returns:
        True or False
    """
    try:
        # Send a GET request to the website with a specified timeout
        response = requests.get(url, timeout=timeout)
        # Check if the response is successful
        if response.status_code == 200: # Status code 200 indicates success
            # Inform the user that the website is up
            display_text_color(f"✅ Website {url} is UP", Fore.GREEN)
            return True
        else:
            # Indicate an issue with the response
            display_text_color(f"⚠️ Website {url} is RESPONDING but with issues: {response.status_code}", Fore.YELLOW)
            return False
    except requests.exceptions.ConnectionError:  # Handle connection errors specifically
        display_alarm_color(f"❌ Website {url} is DOWN or not reachable (DNS issues)", Fore.RED)
    except requests.exceptions.Timeout:  # Notify the user that the site is down
        # Handle timeout errors
        display_alarm_color(f"❌ Website {url} is DOWN or not reachable (Timeout)", Fore.RED)
    except requests.exceptions.RequestException as e:  # Catch all other request-related exceptions
        # Provide details of the error
        display_alarm_color(f"❌ Website {url} is DOWN or not reachable (Request Exception): {str(e)}", Fore.RED)
    return False  # Return false if the website is down or not reachable

def connected_to_internet(url='http://www.google.com/', timeout=5):
    """Check if the system is connected to the internet by making a HEAD request to a URL.

    Args:
        url (str): The URL to check for internet connectivity (default is Google).
        timeout (int): The timeout for the request in seconds (default is 5).

    Returns:
        bool: True if connected, False otherwise.
    """
    display_text_color("Checking internet connection...",
                       Fore.BLACK)  # Indicate the start of the connection check
    try:
        # Make a HEAD request to the URL to check connectivity
        _ = requests.head(url, timeout=timeout)
        # Notify successful connection
        display_text_color(f"🌍 Connected to the internet", Fore.GREEN)
        return True  # Return True indicating successful connection
    except requests.ConnectionError:  # Catch connection errors
        # Notify the user of connection failure
        display_alarm_color("No internet connection available.")
        # Return False indicating no connection
        return False

def get_dns_info():
    """Get DNS server information"""
    try:
        # Check the platform to determine how to get DNS information
        display_text_color("Fetching DNS server information...", Fore.BLACK)
        if platform.system() == "Windows":
            # Windows - use nslookup to get DNS information
            result = subprocess.run(
                # Run nslookup command
                ['nslookup', 'google.com'], capture_output=True, text=True)
            # Display the DNS information
            display_text_color("DNS Information:", Fore.CYAN)
            display_text_color(result.stdout)  # Display the output of nslookup
        else:
            # Non-Windows - read /etc/resolv.conf for DNS information
            display_text_color("Fetching DNS information from /etc/resolv.conf...", Fore.BLACK)
            try:
                with open('/etc/resolv.conf', 'r') as f:  # Open the resolv.conf file
                    dns_info = f.read()  # Read DNS configuration

                # Display the DNS information
                display_text_color("DNS Information:", Fore.CYAN)
                # Display the DNS configuration read from the file
                if dns_info:
                    # Display the DNS information in yellow color
                    display_text_color(dns_info, Fore.YELLOW)
            except:
                dns_info = "Could not read DNS configuration"  # Handle file read errors
                display_alarm_color(f"Error reading DNS configuration: {dns_info}", Fore.RED)
    except Exception as e:
        # Handle any other exceptions
        display_alarm_color(f"Error getting DNS info: {str(e)}", Fore.RED)

def get_system_info():
    """Get system information"""
    import psutil # Import psutil for system information
    import platform # Import platform for OS information
    try:
        # Get system information using psutil and platform
        display_text_color("Fetching system information...", Fore.BLACK)
        # Get OS, CPU, and memory information
        logical_cores = psutil.cpu_count(
            logical=True)  # Count logical CPU cores
        physical_cores = psutil.cpu_count(
            logical=False)  # Count physical CPU cores
        max_frequency = psutil.cpu_freq().max  # Get maximum CPU frequency
        memory = psutil.virtual_memory()  # Get memory usage information
        # Get disk usage information for the root partition
        disk = psutil.disk_usage('/')
        display_text_color(
            "Fetching OS, CPU and memory information...", Fore.BLACK)
        display_text_color(
            # Display OS information
            f"Operating System: {platform.system()} {platform.release()}", Fore.CYAN)
        # Display CPU model
        display_text_color(f"CPU Model: {platform.processor()}", Fore.CYAN)
        # Display CPU architecture
        display_text_color(
            f"CPU Architecture: {platform.architecture()[0]}", Fore.CYAN)
        # Display logical cores count
        display_text_color(f"Logical Cores: {logical_cores}", Fore.CYAN)
        # Display physical cores count
        display_text_color(f"Physical Cores: {physical_cores}", Fore.CYAN)
        # Display max frequency in MHz
        display_text_color(f"Max Frequency: {max_frequency} MHz", Fore.CYAN)
        # Display total memory in GB
        display_text_color(
            f"Total Memory (GB): {round(memory.total / (1024 ** 3), 2)}%", Fore.YELLOW)
        # Display Available memory in GB
        display_text_color(
            f"Available Memory (GB): {round(memory.available / (1024 ** 3), 2)}%", Fore.YELLOW)
        # Display Used memory in GB
        display_text_color(
            f"Used Memory (GB): {round(memory.used / (1024 ** 3), 2)}%", Fore.YELLOW)
        # Display memory usage percentage
        display_text_color(f"Memory Usage: {memory.percent}%", Fore.YELLOW)
        # Total disk space in GB
        display_text_color(
            f"Total Disk Space (GB): {round(disk.total / (1024 ** 3), 2)}%", Fore.YELLOW)
        # Used disk space in GB
        display_text_color(
            f"Used Disk Space (GB): {round(disk.used / (1024 ** 3), 2)}%", Fore.YELLOW)
        # Free disk space in GB
        display_text_color(
            f"Free Disk Space (GB): {round(disk.free / (1024 ** 3), 2)}%", Fore.YELLOW)
        # Disk usage percentage
        display_text_color(f"Disk Usage: {disk.percent}%", Fore.YELLOW)
    except ImportError:
        # Notify if psutil is missing
        display_alarm_color("Install 'pip install psutil' for system info", Fore.RED)
    except Exception as e:
        # Handle any other exceptions
        display_alarm_color(f"Error getting system info: {str(e)}", Fore.RED)


def network_info():
    """Get network information"""
    try:
        import psutil  # Import psutil to access network interface information
        # Get network interface information using psutil
        display_text_color("Fetching network interface information...", Fore.BLACK)
        # Retrieve network interface addresses
        interfaces = psutil.net_if_addrs()
        # Check if any interfaces were found
        if not interfaces:
            display_alarm_color("No network interfaces found.", Fore.RED)
            return  # Exit if no interfaces are found
        # Header for interface information
        display_text_color("Network Interfaces:", Fore.CYAN)
        # Iterate through the interfaces and their addresses
        for interface_name, addresses in interfaces.items():
            # Iterate through the interface addresses
            for addr in addresses:
                # Display interface information
                display_text_color(f"Interface: {interface_name}", Fore.CYAN)
                # Address family (IPv4/IPv6)
                display_text_color(f"  Family: {addr.family}", Fore.YELLOW)
                # IP address
                display_text_color(f"  Address: {addr.address}", Fore.YELLOW)
                # Subnet mask
                display_text_color(f"  Netmask: {addr.netmask}", Fore.YELLOW)
                # Broadcast address (if available)
                if addr.broadcast:
                    # Display broadcast address if it exists
                    display_text_color(
                        f"  Broadcast: {addr.broadcast}", Fore.YELLOW)
                else:
                    # Display "None" if broadcast address is not available
                    display_text_color("  Broadcast: None", Fore.YELLOW)
        # Notify that the interface information has been fetched successfully
        display_text_color("Network interface information fetched successfully.", Fore.GREEN)
    except ImportError:
        # Notify if psutil is missing
        interface_info = {
            "note": "Install 'pip install psutil' for detailed interface info"}
        display_alarm_color(interface_info, Fore.RED)
    except Exception as e:
        # Handle any other exceptions
        display_alarm_color(f"Error getting network info: {str(e)}", Fore.RED)

def free_dictionary_lookup(word):
    """Look up a word in the free dictionary API and display its details.

    Args:
        word (str): The word to look up.
    """
    # Indicate the word being looked up
    display_text_color(
        f"Looking up word: {word}", Fore.BLACK)
    # Check if the word is empty or contains only whitespace
    if not word.strip():
        display_alarm_color("Please provide a valid word to look up.", Fore.RED)
        return

    import requests  # Import requests to make HTTP requests
    # Construct the URL for the free dictionary API
    # API endpoint
    url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}"
    # Send a GET request to the API
    response = requests.get(url)
    # Check if the response status code is not 200 (OK)
    # If the word is not found, the API returns a 404 status code
    if response.status_code != 200:
        # Notify if the word isn't found
        display_text_color(f"Word '{word}' not found.")
        return
    # If the response is successful
    if response.status_code == 200:
        # Display the word being looked up
        display_text_color(f"Word found: {word}", Fore.GREEN)
    try:
        # If the response is successful, parse the JSON data
        data = response.json()[0] # Extract the first entry from the response
        # Display the word
        display_text_color(f"Word: {data['word']}")

        # Phonetic and Audio
        phonetics = data.get("phonetics", [])  # Get phonetic information
        for p in phonetics:
            # Get phonetic text and audio URL
            text = p.get("text")
            audio = p.get("audio")
            if text: # Display phonetic text if available
                display_text_color(f"Phonetic: {text}")
            if audio: # Display audio URL if available
                display_text_color(f"Audio: {audio}")

        # Meanings, Synonyms, Antonyms, Examples:
        for meaning in data.get("meanings", []):  # Iterate through meanings
            pos = meaning.get("partOfSpeech")  # Get part of speech
            print(f"\nPart of Speech: {pos}")
            # Iterate through definitions
            for definition in meaning.get("definitions", []):
                # Get definition, example, synonyms, and antonyms
                def_text = definition.get("definition")
                example = definition.get("example")
                synonyms = definition.get("synonyms", [])
                antonyms = definition.get("antonyms", [])
                # Display definition
                display_text_color(f"  Definition: {def_text}")
                if example:  # Display example if available
                    display_text_color(f"    Example: {example}")
                if synonyms:  # Display synonyms if available
                    display_text_color(f"    Synonyms: {', '.join(synonyms)}")
                if antonyms:  # Display antonyms if available
                    display_text_color(f"    Antonyms: {', '.join(antonyms)}")
    except ValueError:
        # Handle JSON decoding errors
        display_alarm_color("Error decoding JSON response from the dictionary API.", Fore.RED)
        return
    except KeyError:
        # Handle missing keys in the JSON response
        display_alarm_color("Unexpected response format from the dictionary API.", Fore.RED)
    except Exception as e:
        # Handle any other exceptions that may occur
        display_alarm_color(f"An error occurred while looking up the word: {str(e)}", Fore.RED)
    # Return None to indicate successful completion of the function
    return "None"

def today():
    """Get today's date, display the current month, a quote, weather information, news, stocks, and system information.

    Returns:
        None.
    """
    # Get the current date and time
    timestamp = datetime.now().strftime(
        "%Y-%m-%d %H:%M:%S")
    # Display the current date and time in cyan color
    display_text_color("Today is " + timestamp, Fore.CYAN)
    # Display a horizontal ruler with the current date
    text_horizontalRuler(f"Today is {timestamp}")

    # Print the calendar for the current month
    print(calendar.month(datetime.now().year, datetime.now().month))
    # Get a random quote from the quote library
    quote_text = select_quote()
    # Display the quote in yellow color
    display_text_color(quote_text, Fore.YELLOW)

    display_text_color("Fetching weather information...", Fore.BLACK)
    city = "Malaga"
    # Fetch weather data from wttr.in API for the specified city
    response = requests.get(f"https://wttr.in/{city}?format=3")
    # Display the weather information for the specified city in magenta color
    display_text_color(response.text, Fore.MAGENTA)
    # Notify that news is being fetched
    display_text_color("Fetching today's news headlines...", Fore.BLACK)
    news() # Call the news function to display news headlines
    # Notify that stock prices are being fetched
    display_text_color("Fetching today's stock prices...", Fore.BLACK)
    stocks() # Call the stocks function to display stock prices
    # Notify that the specified website is being checked
    display_text_color("Checking website status...", Fore.BLACK)
    # Check the status of the specified website
    check_website_status("https://justtothepoint.com", timeout=10)

    # Notify that internet connection is being checked
    display_text_color("Checking internet connection...", Fore.BLACK)
    # Call the function to check internet connectivity
    connected_to_internet()

    # Notify that system information is being fetched
    display_text_color("Fetching system information...", Fore.BLACK)
    network_info() # Display network interface information
    get_dns_info() # Get DNS server information
    get_system_info() # Get CPU, memory, and disk usage information

if __name__ == "__main__":
    # Call the today function to display today's date, display the current month, a quote, weather information, news, stocks, and system information
    today()
    # Call the free_dictionary_lookup function to look up a word
    free_dictionary_lookup("big")  
Bitcoin donation

JustToThePoint Copyright © 2011 - 2025 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.