Private AI in 30 Minutes

Ever built your own AI server in the time it takes to binge an episode of Netflix?
I just did.

Step 1: Order a no-OS mini PC from Amazon (aka a blank little cube of potential).
Step 2: Throw Ubuntu on it → instant life.
Step 3: Sprinkle CasaOS on top → suddenly it thinks it’s a full-blown home cloud.

Now I’m running:
⚡ Ollama (local LLMs in my house)
🔍 DeepSeek (reasoning + digging power)
📚 TaskingAI (my own private RAG brain for personal data)

The punchline? *Private AI in 30 minutes.
(*Not counting waiting on Amazon. 😏)

For less than the cost of a couple SaaS subscriptions, my living room is rocking a server that feels like Tony Stark’s garage.

Who else is ready to build their own AI batcave? 🦇⚡

 

 

🔥 Private AI in 30 Minutes (Quick Start Guide)

*Not counting waiting on Amazon 😏

1. Get the Hardware

Buy a no-OS mini PC from Amazon (Intel N100 or similar). Plug in keyboard, mouse, monitor.

2. Install Ubuntu

  1. Download Ubuntu 24.04 ISO.
  2. Flash it to a USB stick with Rufus (Windows) or dd (Linux/Mac).
  3. Boot mini PC, install Ubuntu with defaults.
  4. Update system:
sudo apt update && sudo apt upgrade -y

3. Install CasaOS

CasaOS turns your box into a home cloud with an app store:

curl -fsSL https://get.casaos.io | sudo bash

Access CasaOS at: http://your_local_ip

4. Install Ollama

Run LLMs locally:

curl -fsSL https://ollama.com/install.sh | sh

5. Add DeepSeek Model

ollama pull deepseek-r1

Run it with:

ollama run deepseek-r1

6. Install TaskingAI (Self-Hosted RAG Server)

Prereqs: Docker + Docker Compose

sudo apt install docker.io docker-compose git -y

Install TaskingAI:

git clone https://github.com/TaskingAI/TaskingAI.git
cd TaskingAI
docker-compose up -d

Access at: http://your_local_ip:3000

7. Wire It Together

Upload your docs/data into TaskingAI. Use DeepSeek via Ollama as the model. Now you’ve got your own private RAG AI running fully on your LAN!

 

Gmail_Contact_Extractor
Build a Python Gmail Contact Extractor with a GUI
Gmail_Contact_Extractor
Out of respect for data privacy I used a screenshot that only listed the LinkedIn emails found however it was able to extract an email for every single sender I have ever received a message from.

 

Welcome to PrometheanLink! In this comprehensive guide, we’ll walk you through building a Python application that connects to your Gmail account, reads all messages, and extracts names and email addresses. We’ll enhance this application with a user-friendly graphical interface (GUI) using Tkinter, making it accessible even if you’re not deeply familiar with command-line operations.

1. Prerequisites

Before we begin, ensure you have the following:

  • Python 3.6 or higher: Download and install from python.org.
  • A Google Account: You’ll need access to Gmail.
  • Basic Knowledge of Python: Familiarity with Python scripting will be beneficial.</

2. Setting Up the Google API

To interact with Gmail programmatically, we need to set up a project in the Google Cloud Console and obtain the necessary credentials. Follow these steps:

Step 1: Create a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Click on the project dropdown at the top and select “New Project”.
  3. Enter a project name, e.g., “GmailContactExtractor”, and click “Create”.

Step 2: Enable the Gmail API

  1. Within your newly created project, navigate to APIs & Services > Library in the sidebar.
  2. Search for “Gmail API” and select it from the search results.
  3. Click the “Enable” button to activate the API for your project.

Step 3: Configure OAuth Consent Screen

  1. Go to APIs & Services > OAuth consent screen in the sidebar.
  2. Select “External” as the user type and click “Create”.
  3. Fill in the required details:
    • App name: e.g., “Gmail Contact Extractor”
    • User support email: Your email address.
    • Developer contact information: Your email address.
  4. Click “Save and Continue” through the scopes and test users sections, accepting defaults.

Step 4: Create OAuth 2.0 Credentials

  1. Navigate to APIs & Services > Credentials.
  2. Click on “Create Credentials” and select “OAuth client ID”.
  3. Select “Desktop app” as the application type and provide a name, e.g., “GmailContactExtractorApp”.
  4. Click “Create”.
  5. After creation, click “OK” and then download the credentials.json file by clicking the download icon next to your newly created credentials.
  6. Save the credentials.json file in your project directory. Keep this file secure!

3. Installing Required Python Libraries

We’ll need several Python libraries to build and run our application. Open your terminal or command prompt and execute the following commands:

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Note: If you’re using Python 3 and encounter issues, you might need to use pip3 instead of pip.

4. Building the GUI Application

We’ll use Tkinter, Python’s standard GUI library, to create a user-friendly interface. The application will allow users to authenticate with Gmail, scan emails, extract contacts, display them, and export the results to a CSV file.

Complete Python Script

Below is the complete Python script for the GUI-based Gmail Contact Extractor:


import os
import base64
import re
import csv
import threading
from email import message_from_bytes
from email.utils import parseaddr
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# Define the scopes
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
class GmailContactExtractorApp:
    def __init__(self, master):
        self.master = master
        self.master.title("Gmail Contact Extractor")
        self.master.geometry("800x600")
        self.contacts = set()
        # Create GUI components
        self.create_widgets()
    def create_widgets(self):
        # Frame for buttons
        button_frame = tk.Frame(self.master)
        button_frame.pack(pady=10)
        # Login Button
        self.login_button = tk.Button(button_frame, text="Login with Gmail", command=self.authenticate_gmail)
        self.login_button.pack(side=tk.LEFT, padx=10)
        # Export Button
        self.export_button = tk.Button(button_frame, text="Export to CSV", command=self.export_contacts, state=tk.DISABLED)
        self.export_button.pack(side=tk.LEFT, padx=10)
        # Progress Bar
        self.progress = ttk.Progressbar(self.master, orient='horizontal', mode='determinate', length=700)
        self.progress.pack(pady=10)
        # Status Label
        self.status_label = tk.Label(self.master, text="Status: Not authenticated.")
        self.status_label.pack()
        # Treeview for displaying contacts
        columns = ("Name", "Email Address")
        self.tree = ttk.Treeview(self.master, columns=columns, show='headings')
        self.tree.heading("Name", text="Name")
        self.tree.heading("Email Address", text="Email Address")
        self.tree.column("Name", width=200)
        self.tree.column("Email Address", width=400)
        self.tree.pack(pady=10, fill=tk.BOTH, expand=True)
        # Add scrollbar
        scrollbar = ttk.Scrollbar(self.tree, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    def authenticate_gmail(self):
        """Authenticate the user and start the contact extraction process."""
        self.login_button.config(state=tk.DISABLED)
        self.status_label.config(text="Status: Authenticating...")
        threading.Thread(target=self._authenticate_and_extract).start()
    def _authenticate_and_extract(self):
        """Handles authentication and extraction in a separate thread."""
        creds = None
        try:
            # Check if token.json exists
            if os.path.exists('token.json'):
                creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            # If no valid credentials, initiate login
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'credentials.json', SCOPES)
                    creds = flow.run_local_server(port=0)
                # Save the credentials for future use
                with open('token.json', 'w') as token:
                    token.write(creds.to_json())
            # Build the Gmail service
            service = build('gmail', 'v1', credentials=creds)
            self.status_label.config(text="Status: Fetching messages...")
            messages = self.get_all_messages(service)
            total_messages = len(messages)
            self.progress.config(maximum=total_messages)
            self.status_label.config(text=f"Status: Processing {total_messages} messages...")
            for idx, msg in enumerate(messages, start=1):
                mime_msg = self.get_message(service, msg['id'])
                if mime_msg:
                    contacts = self.extract_contacts(mime_msg)
                    self.contacts.update(contacts)
                # Update progress bar
                self.progress['value'] = idx
                self.master.update_idletasks()
            self.status_label.config(text=f"Status: Extraction complete. {len(self.contacts)} contacts found.")
            self.populate_treeview()
            self.export_button.config(state=tk.NORMAL)
        except Exception as e:
            messagebox.showerror("Error", f"An error occurred: {e}")
            self.status_label.config(text="Status: Error occurred.")
            self.login_button.config(state=tk.NORMAL)
    def get_all_messages(self, service, user_id='me'):
        """Retrieve all messages from the user's mailbox."""
        messages = []
        try:
            response = service.users().messages().list(userId=user_id, maxResults=500).execute()
            if 'messages' in response:
                messages.extend(response['messages'])
            # Handle pagination
            while 'nextPageToken' in response:
                page_token = response['nextPageToken']
                response = service.users().messages().list(userId=user_id, pageToken=page_token, maxResults=500).execute()
                if 'messages' in response:
                    messages.extend(response['messages'])
        except Exception as error:
            print(f'An error occurred while fetching messages: {error}')
        return messages
    def get_message(self, service, msg_id, user_id='me'):
        """Retrieve a full message by ID."""
        try:
            message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
            msg_raw = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
            mime_msg = message_from_bytes(msg_raw)
            return mime_msg
        except Exception as error:
            print(f'An error occurred while fetching message {msg_id}: {error}')
            return None
    def extract_contacts(self, mime_msg):
        """Extract names and email addresses from a MIME message."""
        contacts = set()
        headers = ['From', 'To', 'Cc', 'Bcc']
        for header in headers:
            header_value = mime_msg.get(header)
            if header_value:
                # Split multiple addresses
                addresses = header_value.split(',')
                for addr in addresses:
                    name, email = parseaddr(addr)
                    email = email.lower()
                    if email:
                        contacts.add((name.strip(), email))
        # Optionally, extract from the email body
        if mime_msg.is_multipart():
            for part in mime_msg.walk():
                if part.get_content_type() == 'text/plain':
                    try:
                        body = part.get_payload(decode=True).decode('utf-8', errors='ignore')
                        contacts.update(self.extract_contacts_from_text(body))
                    except Exception as e:
                        print(f'Error decoding part of the message: {e}')
        else:
            try:
                body = mime_msg.get_payload(decode=True).decode('utf-8', errors='ignore')
                contacts.update(self.extract_contacts_from_text(body))
            except Exception as e:
                print(f'Error decoding message body: {e}')
        return contacts
    def extract_contacts_from_text(self, text):
        """Extract email addresses and attempt to find associated names in the text."""
        contacts = set()
        # Simple regex to find email addresses
        email_regex = r'[\w\.-]+@[\w\.-]+\.\w+'
        emails = re.findall(email_regex, text)
        for email in emails:
            contacts.add(('', email.lower()))  # Names may not be present in the body
        return contacts
    def populate_treeview(self):
        """Populate the Treeview with extracted contacts."""
        # Clear existing data
        for item in self.tree.get_children():
            self.tree.delete(item)
        # Insert new data
        for name, email in sorted(self.contacts, key=lambda x: x[1]):
            self.tree.insert('', tk.END, values=(name, email))
    def export_contacts(self):
        """Export the contacts to a CSV file."""
        if not self.contacts:
            messagebox.showwarning("No Contacts", "There are no contacts to export.")
            return
        # Ask user where to save the CSV
        file_path = filedialog.asksaveasfilename(defaultextension='.csv',
                                                 filetypes=[('CSV files', '*.csv')],
                                                 title="Save Contacts As")
        if file_path:
            try:
                with open(file_path, mode='w', newline='', encoding='utf-8') as csvfile:
                    contact_writer = csv.writer(csvfile)
                    contact_writer.writerow(['Name', 'Email Address'])
                    for name, email in sorted(self.contacts, key=lambda x: x[1]):
                        contact_writer.writerow([name, email])
                messagebox.showinfo("Success", f"Contacts have been exported to {file_path}")
            except Exception as e:
                messagebox.showerror("Error", f"Failed to export contacts: {e}")
def main():
    root = tk.Tk()
    app = GmailContactExtractorApp(root)
    root.mainloop()
if __name__ == '__main__':
    main()
        

Understanding the Script

Let’s break down the main components of the application:

Imports

We import necessary modules for handling emails, regular expressions, threading, GUI components, and interacting with Google’s API.

Here is the library in case your IDE doesn’t automatically locate it. https://pypi.org/project/google-api-python-client/#files

SCOPES

Defines the permissions the application is requesting. In this case, read-only access to Gmail.

GmailContactExtractorApp Class

This class encapsulates all functionalities of the application, including GUI creation, authentication, email processing, contact extraction, and exporting.

  • __init__: Initializes the GUI components and sets up the application window.
  • create_widgets: Constructs the GUI elements, including buttons, progress bar, status label, and the Treeview for displaying contacts.
  • authenticate_gmail: Triggered when the user clicks the “Login with Gmail” button. Disables the button and starts a new thread for authentication and extraction.
  • _authenticate_and_extract: Handles the authentication flow and contact extraction in a separate thread to keep the GUI responsive.
  • get_all_messages: Fetches all email messages from the user’s Gmail account, handling pagination.
  • get_message: Retrieves the raw content of a specific email message and parses it into a MIME message.
  • extract_contacts: Extracts names and email addresses from email headers and optionally from the email body.
  • extract_contacts_from_text: Uses a regex to find email addresses within a block of text.
  • populate_treeview: Displays the extracted contacts in the Treeview widget.
  • export_contacts: Allows users to export the displayed contacts to a CSV file using a file dialog.

Main Function

Initializes the Tkinter root window and starts the application.

def main():
    root = tk.Tk()
    app = GmailContactExtractorApp(root)
    root.mainloop()
if __name__ == '__main__':
    main()

5. Running the Application

Follow these steps to run your newly created Gmail Contact Extractor:

Step 1: Ensure Credentials Are in Place

Make sure the downloaded credentials.json file is in the same directory as your Python script.

Step 2: Execute the Script

  1. Open your terminal or command prompt.
  2. Navigate to your project directory using the cd command.
  3. Run the script with the following command:
python gmail_contact_extractor.py

Step 3: Authenticate with Gmail

  1. Click the “Login with Gmail” button in the application window.
  2. A browser window will open prompting you to sign in to your Google account and grant the requested permissions.
  3. After successful authentication, the application will begin scanning your emails.

Step 4: Monitor Progress

The progress bar will indicate the scanning progress, and the status label will provide real-time updates.

Step 5: View Extracted Contacts

Once scanning is complete, the extracted names and email addresses will populate the table in the GUI.

Step 6: Export Contacts

  1. Click the “Export to CSV” button.
  2. Select a destination and filename for the CSV file.
  3. The contacts will be saved accordingly.

Note: The initial run might take some time, especially if you have a large number of emails. Subsequent runs will be faster due to cached credentials.

6. Enhancements and Best Practices

While the provided application is functional, consider the following enhancements and best practices for a more robust and user-friendly experience:

Asynchronous Operations

Current Implementation: Uses threading to prevent the GUI from freezing during long operations.

Enhancement: Implement more sophisticated asynchronous handling, possibly using asyncio, for better performance.

Error Handling

Current Implementation: Basic error handling with message boxes.

Enhancement: Implement logging to a file for debugging purposes and provide more detailed error messages.

User Feedback

Enhancement: Display the number of contacts found dynamically or show contacts being added in real-time.

Filtering and Search

Enhancement: Add search functionality within the Treeview to allow users to find specific contacts quickly.

Pagination in Treeview

Enhancement: For very large contact lists, implement pagination or virtual scrolling to improve performance.

Advanced Export Options

Enhancement: Allow exporting in different formats such as Excel (.xlsx) or JSON.

Improved UI Design

Enhancement: Use advanced GUI frameworks like PyQt or Kivy for a more modern and feature-rich interface.

Incremental Scanning

Enhancement: Implement functionality to scan only new or unread emails in subsequent runs to save time.

Data Privacy

Best Practice: Inform users about how their data is handled and ensure compliance with privacy regulations.

Unit Testing

Best Practice: Write unit tests for critical functions to ensure reliability.

7. Conclusion

Congratulations! You’ve successfully built a Python application that connects to your Gmail account, scans your emails, extracts names and email addresses, and presents them in a user-friendly GUI. This tool can serve as a foundation for more advanced applications, such as contact management systems, data analysis tools, or personalized communication platforms.

Remember:

  • Keep your credentials.json and token.json files secure. Do not share them or commit them to public repositories.
  • Handle extracted data responsibly to maintain privacy and adhere to best practices.
  • Explore further enhancements to tailor the application to your specific needs.

If you encounter any issues or have further questions, feel free to reach out or explore more resources on our website.

Happy coding!

 

Protected: Automate Stock Monitoring with Python (request password-orange form on right)

This content is password-protected. To view it, please enter the password below.

PHP File Comparison Tool: Effortlessly Identify Code Differences with This Python Script
php file comparison tool by PrometheanLink
php file comparison tool by PrometheanLink

 

PHP File Comparator Tool

Placeholder ImageWelcome Coders to the PrometheanLink Blog. This page introduces a tool I’ve built to help you compare two PHP files easily. Follow the instructions below to use it, and you’ll find the full Python script available for copying at the end of the page.

Instructions

  1. Ensure you have Python installed on your computer along with the tkinter module.
  2. Copy the script provided below into a Python file (e.g., php_file_comparator.py).
  3. Run the script using your preferred Python IDE or the command line (python php_file_comparator.py).
  4. Use the “Browse” buttons to select the two PHP files you want to compare.
  5. Click the “Compare” button to display the differences between the files.
  6. Use the “Save Results” button to save the comparison output as a text file, if needed.
  7. Click “Clear” to reset the result area.

Python Script

Below is the full Python script for the PHP File Comparator Tool. Copy and paste this into your Python environment to start using the tool:

import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import difflib
def select_file1():
    file_path = filedialog.askopenfilename(title="Select the first PHP file", filetypes=[("PHP Files", "*.php"), ("All Files", "*.*")])
    if file_path:
        file1_entry.delete(0, tk.END)
        file1_entry.insert(0, file_path)
def select_file2():
    file_path = filedialog.askopenfilename(title="Select the second PHP file", filetypes=[("PHP Files", "*.php"), ("All Files", "*.*")])
    if file_path:
        file2_entry.delete(0, tk.END)
        file2_entry.insert(0, file_path)
def compare_files():
    file1_path = file1_entry.get()
    file2_path = file2_entry.get()
    if not file1_path or not file2_path:
        messagebox.showerror("Error", "Please select both files before comparing.")
        return
    try:
        with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
            file1_lines = file1.readlines()
            file2_lines = file2.readlines()
        differ = difflib.unified_diff(
            file1_lines,
            file2_lines,
            fromfile="File 1",
            tofile="File 2",
            lineterm=''
        )
        
        result_text.delete(1.0, tk.END)
        result_text.insert(tk.END, "Differences Found:\n\n")
        for diff in differ:
            if diff.startswith("@@"):
                # Line number information
                result_text.insert(tk.END, f"Line info: {diff}\n", "highlight")
            elif diff.startswith("-"):
                # Lines removed from file 1
                result_text.insert(tk.END, f"Removed: {diff}\n", "removed")
            elif diff.startswith("+"):
                # Lines added to file 2
                result_text.insert(tk.END, f"Added: {diff}\n", "added")
            else:
                result_text.insert(tk.END, f"{diff}\n")
    except Exception as e:
        messagebox.showerror("Error", f"An error occurred while comparing files:\n{e}")
def clear_results():
    result_text.delete(1.0, tk.END)
def save_results():
    result_content = result_text.get(1.0, tk.END).strip()
    if not result_content:
        messagebox.showwarning("Warning", "No results to save!")
        return
    
    file_path = filedialog.asksaveasfilename(
        defaultextension=".txt",
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
        title="Save Comparison Results"
    )
    if file_path:
        with open(file_path, 'w') as file:
            file.write(result_content)
        messagebox.showinfo("Success", "Results saved successfully!")
# GUI setup
root = tk.Tk()
root.title("PHP File Comparator")
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)
# File selection fields
file1_label = tk.Label(frame, text="File 1:")
file1_label.grid(row=0, column=0, padx=5, pady=5, sticky="e")
file1_entry = tk.Entry(frame, width=50)
file1_entry.grid(row=0, column=1, padx=5, pady=5)
file1_button = tk.Button(frame, text="Browse", command=select_file1)
file1_button.grid(row=0, column=2, padx=5, pady=5)
file2_label = tk.Label(frame, text="File 2:")
file2_label.grid(row=1, column=0, padx=5, pady=5, sticky="e")
file2_entry = tk.Entry(frame, width=50)
file2_entry.grid(row=1, column=1, padx=5, pady=5)
file2_button = tk.Button(frame, text="Browse", command=select_file2)
file2_button.grid(row=1, column=2, padx=5, pady=5)
# Buttons
compare_button = tk.Button(frame, text="Compare", command=compare_files, bg="lightgreen")
compare_button.grid(row=2, column=1, pady=10)
clear_button = tk.Button(frame, text="Clear", command=clear_results)
clear_button.grid(row=2, column=0, pady=10)
save_button = tk.Button(frame, text="Save Results", command=save_results)
save_button.grid(row=2, column=2, pady=10)
# Results area
result_text = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=80, height=20)
result_text.pack(padx=10, pady=10)
# Text styling
result_text.tag_config("highlight", foreground="blue")
result_text.tag_config("removed", foreground="red")
result_text.tag_config("added", foreground="green")
# Run the application
root.mainloop()