Tag: #Utility

  • iTunes Top Songs & Albums Purchases Python Script

    This Python script fetches and displays the current top songs or albums based on purchases from the iTunes Store. Users can select a category and the number of entries to view, with rankings clearly labeled to reflect purchase trends as of the check date.

    Click to view script…
    #!/usr/bin/env python3
    # iTunes Top Purchases Scraper
    # Purpose: Fetches and displays the current top songs or albums based on purchases from the iTunes Store.
    # Note: This script shows purchase-based rankings, not streaming data.
    
    import requests
    from datetime import datetime
    
    # Define categories with their display names and RSS feed paths
    categories = {
        1: {'name': 'Top Songs (Purchases)', 'path': 'topsongs'},
        2: {'name': 'Top Albums (Purchases)', 'path': 'topalbums'}
    }
    
    def main():
        """Main function to run the iTunes Top Purchases Scraper."""
        # Inform the user that the data reflects purchases, not streaming
        print("Welcome! This script shows top songs or albums based on purchases from the iTunes Store (not streaming data).")
        
        # Display category options
        print("\nSelect a category:")
        for key, value in categories.items():
            print(f"{key}. {value['name']}")
        
        # Get and validate category choice
        choice_input = input("Enter the number of your choice: ")
        try:
            choice = int(choice_input)
            if choice not in categories:
                raise ValueError
        except ValueError:
            print("Invalid choice. Please run the script again and enter 1 or 2.")
            return
        
        category = categories[choice]
        category_name = category['name']
        
        # Get and validate number of entries
        limit_input = input("Enter the number of entries to display (1-100, default 10): ")
        if limit_input.strip() == "":
            limit = 10
        else:
            try:
                limit = int(limit_input)
                if limit < 1 or limit > 100:
                    print("Limit must be between 1 and 100. Using default of 10.")
                    limit = 10
            except ValueError:
                print("Invalid input. Using default of 10.")
                limit = 10
        
        # Construct the RSS feed URL
        url = f"https://itunes.apple.com/us/rss/{category['path']}/limit={limit}/json"
        
        # Record the current date and time
        check_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Fetch data from the iTunes RSS feed
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error fetching data: {e}")
            return
        
        # Extract entries from the JSON response
        feed = data.get('feed', {})
        entries = feed.get('entry', [])
        
        if not entries:
            print("No data available for this category.")
            return
        
        # Display the results
        print(f"\n{category_name} as of {check_date}")
        print(f"{'Rank':<5} {'Name':<50} {'Artist':<30}")
        print("-" * 85)
        
        for i, entry in enumerate(entries, start=1):
            name = entry.get('im:name', {}).get('label', 'N/A')
            artist = entry.get('im:artist', {}).get('label', 'N/A')
            print(f"{i:<5} {name:<50} {artist:<30}")
    
    if __name__ == '__main__':
        main()
  • iOS App Store Comparison Tool Python Script

    This Python script enables users to compare multiple iOS apps by inputting their names, retrieving details like ratings, versions, and descriptions from the iTunes Search API. It displays a side-by-side overview of each app’s name, short description, rating count, rating stars, current version, and the date the check was initiated.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Initialize a list to store app names
    app_names = []
    while True:
        app_name = input("Enter app name: ")
        app_names.append(app_name)
        another = input("Do you want to add another app? (y/n): ").lower()
        if another != 'y':
            break
    
    # Record the current date and time when the check is initiated
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Initialize a list to store app data
    apps_data = []
    
    # Query the iTunes Search API for each app
    for app_name in app_names:
        try:
            response = requests.get(
                "https://itunes.apple.com/search",
                params={"term": app_name, "country": "us", "media": "software"}
            )
            response.raise_for_status()  # Raise an exception for HTTP errors
            data = response.json()
    
            if data["resultCount"] > 0:
                # Take the first result as the most relevant app
                app = data["results"][0]
                
                # Create a short description from the first 20 words of the full description
                words = app["description"].split()
                short_description = " ".join(words[:20]) + "..." if len(words) > 20 else " ".join(words)
                
                # Get the rating stars, formatting to one decimal place if available
                rating_stars = app.get("averageUserRating", "N/A")
                if rating_stars != "N/A":
                    rating_stars = f"{rating_stars:.1f}"
                
                # Compile the app information
                app_info = {
                    "app_name": app["trackName"],
                    "short_description": short_description,
                    "rating_count": app.get("userRatingCount", 0),
                    "rating_stars": rating_stars,
                    "current_version": app.get("version", "N/A"),
                    "check_date": current_time
                }
            else:
                app_info = {
                    "app_name": app_name,
                    "error": "App not found"
                }
        except requests.exceptions.RequestException as e:
            app_info = {
                "app_name": app_name,
                "error": f"Error fetching data: {e}"
            }
        
        apps_data.append(app_info)
    
    # Display the information for all apps
    for app_info in apps_data:
        if "error" in app_info:
            print(f"App Name: {app_info['app_name']}")
            print(f"Error: {app_info['error']}")
        else:
            print(f"App Name: {app_info['app_name']}")
            print(f"Short Description: {app_info['short_description']}")
            print(f"Rating Count: {app_info['rating_count']}")
            print(f"Rating Stars: {app_info['rating_stars']}")
            print(f"Current Version: {app_info['current_version']}")
            print(f"Check Date: {app_info['check_date']}")
        print("-" * 40)
  • iOS App Store Rating Checker Python Script

    This Python script allows users to input an iOS app name and retrieves its overall rating and total number of ratings from the iTunes Search API. It also displays the current date and time when the data was checked, providing a simple way to monitor app performance on the App Store.

    Click to view script…
    import requests
    from datetime import datetime
    
    # Get the app name from the user
    app_name = input("Enter the app name: ")
    
    # Base URL for the iTunes Search API
    base_url = "https://itunes.apple.com/search"
    
    # Parameters for the API request
    params = {
        "term": app_name,
        "country": "us",
        "media": "software"
    }
    
    try:
        # Send GET request to the API
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise an exception for HTTP errors
    
        # Parse the JSON response
        data = response.json()
    
        # Check if any apps were found
        if data["resultCount"] > 0:
            # Extract the first app's data
            app = data["results"][0]
            rating = app.get("averageUserRating", "N/A")
            if rating != "N/A":
                rating = f"{rating:.1f}"  # Format rating to one decimal place
            count = app.get("userRatingCount", "N/A")
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
            # Print the results
            print(f"App Name: {app['trackName']}")
            print(f"Overall Rating: {rating}")
            print(f"Total Ratings: {count}")
            print(f"Date Checked: {current_time}")
        else:
            print("No apps found with that name.")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
  • Sleep Pattern Analyzer Python Script

    A Python script to track your sleep patterns by logging bed and wake times, and rate your sleep quality. Get insights like average sleep hours, best sleep nights, and view sleep data for any specific date.

    Click to view script…
    import json
    import os
    from datetime import datetime, timedelta
    
    # Load existing entries from the JSON file
    if os.path.exists("sleep_log.json"):
        with open("sleep_log.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new sleep entry, (2) look up sleep statistics, or (3) view sleep data for a specific date? Enter 1, 2, or 3: ").strip()
    
    if action == "1":
        # Record a new sleep entry
        date_input = input("Enter the date (YYYY-MM-DD) or press enter for today: ").strip()
        if date_input == "":
            date = datetime.now().strftime("%Y-%m-%d")
        else:
            date = date_input  # Assuming correct input for simplicity
    
        bed_time = input("Enter bed time (HH:MM): ").strip()
        wake_time = input("Enter wake time (HH:MM): ").strip()
        
        while True:
            try:
                quality = int(input("Enter quality rating (1-5): "))
                if 1 <= quality <= 5:
                    break
                else:
                    print("Please enter a number between 1 and 5.")
            except ValueError:
                print("Invalid input. Please enter an integer.")
        
        # Calculate hours slept
        bed_dt = datetime.strptime(date + " " + bed_time, "%Y-%m-%d %H:%M")
        wake_dt = datetime.strptime(date + " " + wake_time, "%Y-%m-%d %H:%M")
        if wake_dt < bed_dt:
            wake_dt += timedelta(days=1)
        hours_slept = (wake_dt - bed_dt).total_seconds() / 3600
        
        new_entry = {
            "date": date,
            "bed_time": bed_time,
            "wake_time": wake_time,
            "hours_slept": hours_slept,
            "quality": quality
        }
        entries.append(new_entry)
        
        with open("sleep_log.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Sleep recorded: {hours_slept:.2f} hours with quality {quality}")
        
        if len(entries) > 1:
            prev_entry = entries[-2]
            diff = hours_slept - prev_entry["hours_slept"]
            if diff > 0:
                print(f"You slept {diff:.2f} hours more than the previous night.")
            elif diff < 0:
                print(f"You slept {-diff:.2f} hours less than the previous night.")
            else:
                print("You slept the same number of hours as the previous night.")
    
    elif action == "2":
        # Look up sleep statistics
        if not entries:
            print("No sleep entries found. Please record a sleep entry first.")
        else:
            # Calculate overall average sleep hours
            total_hours = sum(entry["hours_slept"] for entry in entries)
            avg_hours = total_hours / len(entries)
            print(f"Overall average sleep hours: {avg_hours:.2f} hours")
            
            # Average sleep hours in the last 7 days
            today = datetime.now()
            last_7_days = [entry for entry in entries if (today - datetime.strptime(entry["date"], "%Y-%m-%d")).days < 7]
            if last_7_days:
                avg_last_7 = sum(entry["hours_slept"] for entry in last_7_days) / len(last_7_days)
                print(f"Average sleep hours in the last 7 days: {avg_last_7:.2f} hours")
            else:
                print("No entries in the last 7 days.")
            
            # Best night's sleep (longest hours)
            best_hours_entry = max(entries, key=lambda x: x["hours_slept"])
            print(f"Best night's sleep: {best_hours_entry['hours_slept']:.2f} hours on {best_hours_entry['date']}")
            
            # Best quality sleep (highest rating)
            best_quality_entry = max(entries, key=lambda x: x["quality"])
            print(f"Best quality sleep: rating {best_quality_entry['quality']} on {best_quality_entry['date']}")
    
    elif action == "3":
        # View sleep data for a specific date
        if not entries:
            print("No sleep entries found. Please record a sleep entry first.")
        else:
            user_date = input("Enter the date to look up (YYYY-MM-DD): ").strip()
            matching_entries = [entry for entry in entries if entry['date'] == user_date]
            
            if matching_entries:
                print(f"\nSleep data for {user_date}:")
                for entry in matching_entries:
                    print(f"- Bed time: {entry['bed_time']}")
                    print(f"  Wake time: {entry['wake_time']}")
                    print(f"  Hours slept: {entry['hours_slept']:.2f}")
                    print(f"  Quality: {entry['quality']}")
            else:
                print(f"No sleep entries found for {user_date}.")
    
    else:
        print("Invalid choice. Please run the script again and enter 1, 2, or 3.")
  • Food Price Tracker Python Script

    A Python script for recording and analyzing food prices from different locations. Track your favorite dishes, find the cheapest spots, and get insights like average prices per location and the best deal overall.

    Click to view script…
    import json
    import os
    from datetime import datetime
    from statistics import mean
    
    # Load existing entries from the JSON file
    if os.path.exists("food_prices.json"):
        with open("food_prices.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new food price or (2) look up past food prices? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new food price
        food_item = input("Enter the food item: ").strip()
        location = input("Enter the location (restaurant/store): ").strip()
        while True:
            try:
                price = float(input("Enter the price in USD: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        new_entry = {
            "date": date_str,
            "time": time_str,
            "food_item": food_item,
            "location": location,
            "price": price
        }
        entries.append(new_entry)
        
        with open("food_prices.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Food price recorded: {food_item} at {location} for ${price:.2f}")
    
    elif action == "2":
        # Look up past food prices and view statistics
        if not entries:
            print("No food price entries found. Please record a food price first.")
        else:
            lookup_type = input("Do you want to look up by (1) food item or (2) location? Enter 1 or 2: ").strip()
            
            if lookup_type == "1":
                # Look up by food item
                food_item = input("Enter the food item to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["food_item"].lower() == food_item.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {food_item}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['location']} - ${entry['price']:.2f}")
                    
                    # Find the cheapest spot for this food item
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"\nCheapest spot for {food_item}: {cheapest_entry['location']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {food_item}.")
            
            elif lookup_type == "2":
                # Look up by location
                location = input("Enter the location to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["location"].lower() == location.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {location}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['food_item']} - ${entry['price']:.2f}")
                    
                    # Calculate average price at this location
                    prices = [entry["price"] for entry in matching_entries]
                    avg_price = mean(prices)
                    print(f"\nAverage food price at {location}: ${avg_price:.2f}")
                    
                    # Find the cheapest food item at this location
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"Cheapest food item at {location}: {cheapest_entry['food_item']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {location}.")
            
            else:
                print("Invalid choice. Please enter 1 or 2.")
            
            # Overall best deal (cheapest food item overall)
            if entries:
                best_deal = min(entries, key=lambda x: x["price"])
                print(f"\nBest deal overall: {best_deal['food_item']} at {best_deal['location']} for ${best_deal['price']:.2f}")
    
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Drink Price Tracker Python Script

    A Python script for recording and analyzing drink prices. Track your favorite cocktails, find the cheapest spots, and get insights like average prices per location and the best deal of the night.

    Click to view script…
    import json
    import os
    from datetime import datetime
    from statistics import mean
    
    # Load existing entries from the JSON file
    if os.path.exists("drink_prices.json"):
        with open("drink_prices.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new drink price or (2) look up past drink prices? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new drink price
        drink_name = input("Enter the drink name: ").strip()
        location = input("Enter the location (casino/bar): ").strip()
        while True:
            try:
                price = float(input("Enter the price in USD: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        new_entry = {
            "date": date_str,
            "time": time_str,
            "drink": drink_name,
            "location": location,
            "price": price
        }
        entries.append(new_entry)
        
        with open("drink_prices.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Drink price recorded: {drink_name} at {location} for ${price:.2f}")
    
    elif action == "2":
        # Look up past drink prices and view statistics
        if not entries:
            print("No drink price entries found. Please record a drink price first.")
        else:
            lookup_type = input("Do you want to look up by (1) drink name or (2) location? Enter 1 or 2: ").strip()
            
            if lookup_type == "1":
                # Look up by drink name
                drink_name = input("Enter the drink name to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["drink"].lower() == drink_name.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {drink_name}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['location']} - ${entry['price']:.2f}")
                    
                    # Find the cheapest spot for this drink
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"\nCheapest spot for {drink_name}: {cheapest_entry['location']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {drink_name}.")
            
            elif lookup_type == "2":
                # Look up by location
                location = input("Enter the location to look up: ").strip()
                matching_entries = [entry for entry in entries if entry["location"].lower() == location.lower()]
                
                if matching_entries:
                    print(f"\nEntries for {location}:")
                    for entry in matching_entries:
                        print(f"- {entry['date']} {entry['time']}: {entry['drink']} - ${entry['price']:.2f}")
                    
                    # Calculate average price at this location
                    prices = [entry["price"] for entry in matching_entries]
                    avg_price = mean(prices)
                    print(f"\nAverage drink price at {location}: ${avg_price:.2f}")
                    
                    # Find the cheapest drink at this location
                    cheapest_entry = min(matching_entries, key=lambda x: x["price"])
                    print(f"Cheapest drink at {location}: {cheapest_entry['drink']} at ${cheapest_entry['price']:.2f}")
                else:
                    print(f"No entries found for {location}.")
            
            else:
                print("Invalid choice. Please enter 1 or 2.")
            
            # Overall deal of the night (cheapest drink overall)
            if entries:
                deal_of_the_night = min(entries, key=lambda x: x["price"])
                print(f"\nDeal of the night: {deal_of_the_night['drink']} at {deal_of_the_night['location']} for ${deal_of_the_night['price']:.2f}")
    
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Weight Tracking Python Script

    This Python script allows users to record their weight in pounds, automatically converting it to kilograms, and tracks entries over time with timestamps. It also enables users to look up past weights by date, showing changes from previous entries, and stores all data persistently in a JSON file for long-term tracking.

    Click to view script…
    import json
    import os
    from datetime import datetime
    
    def lbs_to_kg(lbs):
        """Convert weight from pounds to kilograms."""
        return lbs * 0.453592
    
    def validate_date(date_str):
        """Validate date input and return a date object if valid."""
        try:
            return datetime.strptime(date_str, "%Y-%m-%d").date()
        except ValueError:
            return None
    
    # Load existing entries from the JSON file
    if os.path.exists("weight_log.json"):
        with open("weight_log.json", "r") as f:
            entries = json.load(f)
    else:
        entries = []
    
    # Ask the user what they want to do
    action = input("Do you want to (1) record a new weight or (2) look up a past weight? Enter 1 or 2: ").strip()
    
    if action == "1":
        # Record a new weight
        while True:
            try:
                weight = float(input("Enter your weight in pounds: "))
                break
            except ValueError:
                print("Invalid input. Please enter a number.")
        
        now = datetime.now()
        date_str = now.strftime("%Y-%m-%d")
        time_str = now.strftime("%H:%M:%S")
        
        if len(entries) > 0:
            previous_weight = entries[-1]["weight_lbs"]
            diff = weight - previous_weight
        else:
            diff = None
        
        new_entry = {"date": date_str, "time": time_str, "weight_lbs": weight}
        entries.append(new_entry)
        
        with open("weight_log.json", "w") as f:
            json.dump(entries, f, indent=4)
        
        print(f"Weight recorded: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
        
        if diff is not None:
            if diff > 0:
                print(f"You gained {diff:.2f} lbs ({lbs_to_kg(diff):.2f} kg) since the last entry.")
            elif diff < 0:
                print(f"You lost {-diff:.2f} lbs ({-lbs_to_kg(diff):.2f} kg) since the last entry.")
            else:
                print("No change in weight since the last entry.")
        else:
            print("This is your first entry. No previous data to compare.")
    
    elif action == "2":
        # Look up a past weight
        if not entries:
            print("No weight entries found. Please record a weight first.")
        else:
            while True:
                date_input = input("Enter the date to look up (YYYY-MM-DD): ")
                lookup_date = validate_date(date_input)
                if lookup_date:
                    break
                else:
                    print("Invalid date format. Please enter the date in YYYY-MM-DD format.")
            
            # Find entries for the specified date
            matching_entries = [entry for entry in entries if entry["date"] == date_input]
            
            if matching_entries:
                print(f"\nWeight entries for {date_input}:")
                for entry in matching_entries:
                    weight = entry["weight_lbs"]
                    time = entry["time"]
                    print(f"- {time}: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
            else:
                print(f"No weight entries found for {date_input}.")
    else:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
  • Apple Product Spec Scraper Python Script

    This Python script searches Wikipedia for an Apple product by name, extracts key specifications like dimensions, weight, and camera details from the infobox, and formats the data for easy reading, with special handling for model-specific variations like “Pro” and “Pro Max.”

    This script relies on four Python libraries: requests fetches data from Wikipedia’s API, BeautifulSoup (from bs4) parses the HTML content to extract infobox details, sys handles command-line arguments for the product name input, and re provides regular expression support to clean up text by removing citation markers and extra whitespace. To install the external libraries, use pip: run pip install requests beautifulsoup4 in your terminal or command prompt, while sys and re are part of Python’s standard library and require no additional installation.

    Click to view script…
    import requests
    from bs4 import BeautifulSoup
    import sys
    import re
    
    # Define the fields we want to show
    desired_fields = [
        "First released",
        "Dimensions",
        "Weight",
        "Operating system",
        "System-on-chip",
        "Memory",
        "Storage",
        "Battery",
        "Rear camera",
        "Front camera",
        "Display",
    ]
    
    # Define fields that have model-specific values (e.g., Pro vs. Pro Max)
    model_specific_fields = ["Dimensions", "Weight", "Battery", "Display"]
    
    def search_wikipedia(query):
        """Search Wikipedia for the given query and return the title of the first result."""
        search_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "query",
            "list": "search",
            "srsearch": query,
            "format": "json"
        }
        response = requests.get(search_url, params=params)
        data = response.json()
        if data['query']['search']:
            return data['query']['search'][0]['title']
        return None
    
    def get_page_html(title):
        """Retrieve the HTML content of the Wikipedia page with the given title."""
        parse_url = "https://en.wikipedia.org/w/api.php"
        params = {
            "action": "parse",
            "page": title,
            "format": "json"
        }
        response = requests.get(parse_url, params=params)
        data = response.json()
        return data['parse']['text']['*']
    
    def extract_infobox(html):
        """Extract key-value pairs from the infobox in the HTML content."""
        soup = BeautifulSoup(html, 'html.parser')
        infobox = soup.find('table', {'class': 'infobox'})
        if infobox:
            rows = infobox.find_all('tr')
            info = {}
            for row in rows:
                header = row.find('th')
                data = row.find('td')
                if header and data:
                    key = header.text.strip()
                    value = data.text.strip()
                    info[key] = value
            return info
        return None
    
    def clean_text(text):
        """Remove citation numbers and extra spaces from the text."""
        return re.sub(r'\[\d+\]', '', text).strip()
    
    def format_model_values(value):
        """Format model-specific values for fields like dimensions, weight, etc."""
        if "Pro Max:" in value:
            pro_part, pro_max_part = value.split("Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- Pro: {pro_value}\n- Pro Max: {pro_max_value}"
        elif "16 Pro Max:" in value:
            pro_part, pro_max_part = value.split("16 Pro Max:", 1)
            pro_value = clean_text(pro_part.replace("16 Pro: ", "", 1).strip())
            pro_max_value = clean_text(pro_max_part.strip())
            return f"- 16 Pro: {pro_value}\n- 16 Pro Max: {pro_max_value}"
        return clean_text(value)
    
    def main():
        if len(sys.argv) < 2:
            print("Usage: python3 apple_product_finder.py <product name>")
            sys.exit(1)
        product_name = " ".join(sys.argv[1:])
        title = search_wikipedia(product_name + " Apple")
        if not title:
            print("No product found.")
            return
        html = get_page_html(title)
        infobox = extract_infobox(html)
        if infobox:
            print(f"Key information for {title}:")
            for key in desired_fields:
                if key in infobox:
                    value = infobox[key]
                    if key in model_specific_fields:
                        formatted_value = format_model_values(value)
                        print(f"{key}:\n{formatted_value}")
                    else:
                        print(f"{key}: {clean_text(value)}")
        else:
            print("No infobox found for this product.")
    
    if __name__ == "__main__":
        main()
  • iTunes TV Show Seasons Release Finder Swift Script

    This Swift script lets you search for a TV show by title from the macOS Terminal, displaying its initial release date and a chronological list of seasons with their release dates, all pulled from the iTunes Store API. Perfect for TV enthusiasts wanting quick access to show timelines!

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response for TV seasons
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [TVSeason]
    }
    
    struct TVSeason: Codable {
        let artistName: String      // The TV show's name
        let collectionName: String  // The season's name
        let releaseDate: Date       // The season's release date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <tv show title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single TV show title
    let tvShowTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL for searching TV seasons
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: tvShowTitle),
        URLQueryItem(name: "media", value: "tvShow"),
        URLQueryItem(name: "entity", value: "tvSeason"),
        URLQueryItem(name: "country", value: "us")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Exit code for the script
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let seasons = searchResponse.results
                    let showName = seasons[0].artistName
                    // Sort seasons by release date
                    let sortedSeasons = seasons.sorted { $0.releaseDate < $1.releaseDate }
                    // Display show info and initial release date
                    if let firstReleaseDate = sortedSeasons.first?.releaseDate {
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateStyle = .long
                        let formattedDate = dateFormatter.string(from: firstReleaseDate)
                        print("TV Show: \(showName)")
                        print("Initial Release Date: \(formattedDate)")
                    } else {
                        print("TV Show: \(showName)")
                        print("Release date not available.")
                    }
                    // List all seasons
                    print("Seasons:")
                    for season in sortedSeasons {
                        let seasonDateFormatter = DateFormatter()
                        seasonDateFormatter.dateStyle = .long
                        let seasonFormattedDate = seasonDateFormatter.string(from: season.releaseDate)
                        print("- \(season.collectionName): \(seasonFormattedDate)")
                    }
                    exitCode = 0
                } else {
                    print("No TV show found for \"\(tvShowTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)

  • iTunes Movie Release Lookup Swift Script

    This Swift script searches the iTunes Store for a movie by title, provided as a command-line argument, and prints the release date of the first matching result. It uses the iTunes Search API and handles errors gracefully with appropriate exit codes

    Click to view script…
    #!/usr/bin/env swift
    
    import Foundation
    
    // Define structs to match the iTunes Search API response
    struct SearchResponse: Codable {
        let resultCount: Int
        let results: [Movie]
    }
    
    struct Movie: Codable {
        let trackName: String
        let releaseDate: Date
    }
    
    // Check for command-line arguments
    if CommandLine.arguments.count < 2 {
        print("Usage: \(CommandLine.arguments[0]) <movie title>")
        exit(1)
    }
    
    // Combine all arguments after the script name into a single movie title
    let movieTitle = CommandLine.arguments[1...].joined(separator: " ")
    
    // Construct the API URL
    let baseURL = "https://itunes.apple.com/search"
    let queryItems = [
        URLQueryItem(name: "term", value: movieTitle),
        URLQueryItem(name: "media", value: "movie"),
        URLQueryItem(name: "entity", value: "movie")
    ]
    var urlComponents = URLComponents(string: baseURL)!
    urlComponents.queryItems = queryItems
    guard let url = urlComponents.url else {
        print("Invalid URL.")
        exit(1)
    }
    
    // Set up semaphore to handle asynchronous URLSession task
    let semaphore = DispatchSemaphore(value: 0)
    var exitCode: Int32 = 0  // Explicitly typed as Int32 to match exit() requirement
    
    // Perform the network request
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            exitCode = 1
        } else if let data = data {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601 // Handle ISO 8601 date format from API
            do {
                let searchResponse = try decoder.decode(SearchResponse.self, from: data)
                if searchResponse.resultCount > 0 {
                    let movie = searchResponse.results[0] // Take the first result
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateStyle = .long
                    let formattedDate = dateFormatter.string(from: movie.releaseDate)
                    print("Release date of \(movie.trackName): \(formattedDate)")
                    exitCode = 0
                } else {
                    print("No results found for \"\(movieTitle)\".")
                    exitCode = 1
                }
            } catch {
                print("Error decoding JSON: \(error)")
                exitCode = 1
            }
        } else {
            print("No data received.")
            exitCode = 1
        }
        semaphore.signal() // Signal completion of the network task
    }
    
    // Start the task and wait for it to complete
    task.resume()
    semaphore.wait()
    exit(exitCode)