Social Media Content Scheduler

Install Dependencies

pip install streamlit schedule selenium

Project Structure

social_scheduler/
├── scheduler.py
├── social_scheduler_app.py
├── database.db  (auto-created)


Streamlit App – social_scheduler_app.py


import streamlit as st
import sqlite3
import datetime

# === DB Setup ===
conn = sqlite3.connect('database.db', check_same_thread=False)
c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS posts
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
              platform TEXT, 
              content TEXT, 
              post_time TEXT)''')
conn.commit()

# === Functions ===
def add_post(platform, content, post_time):
    c.execute("INSERT INTO posts (platform, content, post_time) VALUES (?, ?, ?)", 
              (platform, content, post_time))
    conn.commit()

def get_all_posts():
    c.execute("SELECT * FROM posts ORDER BY post_time")
    return c.fetchall()

def delete_post(post_id):
    c.execute("DELETE FROM posts WHERE id = ?", (post_id,))
    conn.commit()

# === Streamlit UI ===
st.title("๐Ÿ“… Social Media Content Scheduler")

with st.form("post_form"):
    platform = st.selectbox("Platform", ["Twitter", "LinkedIn", "Facebook", "Instagram"])
    content = st.text_area("Post Content", max_chars=500)
    post_time = st.time_input("Post Time (24H)")
    submit = st.form_submit_button("➕ Schedule Post")

    if submit:
        post_datetime = datetime.datetime.combine(datetime.date.today(), post_time)
        add_post(platform, content, post_datetime.strftime("%Y-%m-%d %H:%M:%S"))
        st.success("✅ Post scheduled!")

st.subheader("๐Ÿ“‹ Scheduled Posts")
posts = get_all_posts()
for post in posts:
    st.markdown(f"**[{post[1]}]** {post[2]}  \n⏰ {post[3]}")
    if st.button(f"❌ Delete", key=post[0]):
        delete_post(post[0])
        st.experimental_rerun()

Background Scheduler – scheduler.py

import sqlite3
import schedule
import time
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By

# === Dummy Post Logic ===
def post_to_platform(platform, content):
    print(f"๐ŸŸข Posting to {platform}: {content}")
    # You can replace below with Selenium logic to auto-login and post

# === Actual Scheduler ===
def check_and_post():
    conn = sqlite3.connect('database.db')
    c = conn.cursor()

    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    c.execute("SELECT * FROM posts WHERE post_time <= ?", (now,))
    posts_due = c.fetchall()

    for post in posts_due:
        post_to_platform(post[1], post[2])
        c.execute("DELETE FROM posts WHERE id = ?", (post[0],))

    conn.commit()
    conn.close()

# === Start Scheduler ===
schedule.every(1).minutes.do(check_and_post)

print("⏳ Scheduler running every minute...")
while True:
    schedule.run_pending()
    time.sleep(30)

How to Run It

  1. Start Streamlit App:

        streamlit run social_scheduler_app.py
   
   2. In another terminal, run the scheduler:

        python scheduler.py

Travel Planner with Map Integration

import tkinter as tk

from tkinter import messagebox

import requests

import folium

from geopy.geocoders import Nominatim

import webbrowser


# === API KEY ===

WEATHER_API_KEY = "YOUR_OPENWEATHER_API_KEY"


# === Core Functions ===


def get_coordinates(place):

    geolocator = Nominatim(user_agent="travel_planner")

    location = geolocator.geocode(place)

    if location:

        return (location.latitude, location.longitude)

    return None


def get_weather(city):

    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={WEATHER_API_KEY}&units=metric"

    response = requests.get(url)

    data = response.json()

    if data.get("main"):

        temp = data["main"]["temp"]

        weather = data["weather"][0]["description"]

        return f"{temp}°C, {weather}"

    return "Not found"


def estimate_cost(destinations):

    return len(destinations) * 1500  # ₹1500 per destination (sample logic)


def show_map(destinations):

    if not destinations:

        messagebox.showerror("Error", "No destinations added!")

        return


    m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)


    for city in destinations:

        coord = get_coordinates(city)

        if coord:

            weather = get_weather(city)

            folium.Marker(coord, tooltip=f"{city}: {weather}").add_to(m)

        else:

            messagebox.showwarning("Warning", f"Could not locate {city}")


    # Optional: Add route lines

    coords = [get_coordinates(city) for city in destinations if get_coordinates(city)]

    if len(coords) > 1:

        folium.PolyLine(coords, color="blue", weight=2.5).add_to(m)


    m.save("travel_map.html")

    webbrowser.open("travel_map.html")


# === GUI ===


destinations = []


def add_destination():

    city = city_entry.get()

    if city:

        destinations.append(city)

        city_listbox.insert(tk.END, city)

        city_entry.delete(0, tk.END)


def clear_destinations():

    destinations.clear()

    city_listbox.delete(0, tk.END)


def plan_trip():

    if not destinations:

        messagebox.showwarning("Empty", "Add destinations first.")

        return

    cost = estimate_cost(destinations)

    show_map(destinations)

    messagebox.showinfo("Trip Estimate", f"๐Ÿ—บ️ Trip planned for {len(destinations)} places.\nEstimated Cost: ₹{cost}")


root = tk.Tk()

root.title("๐Ÿงณ Travel Planner")

root.geometry("400x450")


tk.Label(root, text="Enter Destination City").pack(pady=5)

city_entry = tk.Entry(root, width=30)

city_entry.pack(pady=5)


tk.Button(root, text="➕ Add", command=add_destination).pack()

city_listbox = tk.Listbox(root, width=40)

city_listbox.pack(pady=10)


tk.Button(root, text="๐Ÿ—บ️ Plan Trip", command=plan_trip).pack(pady=10)

tk.Button(root, text="❌ Clear All", command=clear_destinations).pack()


root.mainloop()


System Cleanup Scheduler

import os

import shutil

import hashlib

import schedule

import time

from datetime import datetime, timedelta


# === CONFIG ===

TEMP_DIRS = ["temp"]

LOG_DIRS = ["logs"]

DUPLICATE_SCAN_DIRS = ["temp", "logs"]

LOG_EXPIRY_DAYS = 7


# === 1. Delete temp files ===

def clean_temp_folders():

    print("๐Ÿงน Cleaning temp folders...")

    for folder in TEMP_DIRS:

        for filename in os.listdir(folder):

            file_path = os.path.join(folder, filename)

            try:

                if os.path.isfile(file_path) or os.path.islink(file_path):

                    os.remove(file_path)

                    print(f"Deleted file: {file_path}")

                elif os.path.isdir(file_path):

                    shutil.rmtree(file_path)

                    print(f"Deleted folder: {file_path}")

            except Exception as e:

                print(f"❌ Failed to delete {file_path}: {e}")


# === 2. Delete old logs ===

def delete_old_logs():

    print("๐Ÿ“ Deleting old logs...")

    for folder in LOG_DIRS:

        for root, dirs, files in os.walk(folder):

            for file in files:

                file_path = os.path.join(root, file)

                try:

                    file_time = datetime.fromtimestamp(os.path.getmtime(file_path))

                    if datetime.now() - file_time > timedelta(days=LOG_EXPIRY_DAYS):

                        os.remove(file_path)

                        print(f"๐Ÿ—‘️ Removed old log: {file_path}")

                except Exception as e:

                    print(f"❌ Error checking {file_path}: {e}")


# === 3. Delete duplicate files ===

def delete_duplicates():

    print("๐Ÿ” Searching for duplicates...")

    hashes = {}

    for folder in DUPLICATE_SCAN_DIRS:

        for root, _, files in os.walk(folder):

            for file in files:

                path = os.path.join(root, file)

                try:

                    with open(path, 'rb') as f:

                        file_hash = hashlib.md5(f.read()).hexdigest()

                    if file_hash in hashes:

                        os.remove(path)

                        print(f"❌ Duplicate removed: {path}")

                    else:

                        hashes[file_hash] = path

                except Exception as e:

                    print(f"❌ Error reading {path}: {e}")


# === 4. Master cleanup function ===

def run_cleanup():

    print(f"\n๐Ÿ”ง Running system cleanup @ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    clean_temp_folders()

    delete_old_logs()

    delete_duplicates()

    print("✅ Cleanup complete.")


# === 5. Scheduler ===

schedule.every().sunday.at("08:00").do(run_cleanup)


print("๐Ÿ•’ System Cleanup Scheduler started... (Press Ctrl+C to exit)")

run_cleanup()  # Run once on start


while True:

    schedule.run_pending()

    time.sleep(60)


Book Cover & Title Generator

import random

from faker import Faker

from PIL import Image, ImageDraw, ImageFont

import os

import openai


# === CONFIG ===

OUTPUT_FOLDER = "covers"

os.makedirs(OUTPUT_FOLDER, exist_ok=True)

fake = Faker()


# Optional: Set your OpenAI API Key

openai.api_key = "YOUR_API_KEY"  # Replace with your key


# === 1. Generate Book Title ===

def generate_book_title(prompt=None):

    if prompt:

        response = openai.ChatCompletion.create(

            model="gpt-4",

            messages=[{"role": "user", "content": prompt}],

            max_tokens=30

        )

        return response['choices'][0]['message']['content'].strip()

    else:

        adjectives = ["Lost", "Silent", "Hidden", "Broken", "Eternal"]

        nouns = ["Dream", "Kingdom", "Secret", "Shadow", "Memory"]

        return f"The {random.choice(adjectives)} {random.choice(nouns)}"


# === 2. Generate Author Name ===

def generate_author_name():

    return fake.name()


# === 3. Generate Cover Image ===

def generate_cover_image(title, author, background="background.jpg"):

    WIDTH, HEIGHT = 600, 900

    cover = Image.new("RGB", (WIDTH, HEIGHT), "white")


    try:

        bg = Image.open(background).resize((WIDTH, HEIGHT))

        cover.paste(bg)

    except:

        print("⚠️ No background image found. Using plain white.")


    draw = ImageDraw.Draw(cover)


    try:

        title_font = ImageFont.truetype("arial.ttf", 40)

        author_font = ImageFont.truetype("arial.ttf", 30)

    except:

        title_font = ImageFont.load_default()

        author_font = ImageFont.load_default()


    # Draw title

    draw.text((40, HEIGHT // 3), title, font=title_font, fill="black", spacing=2)


    # Draw author

    draw.text((40, HEIGHT // 3 + 100), f"by {author}", font=author_font, fill="darkgray")


    filename = os.path.join(OUTPUT_FOLDER, f"{title[:20].replace(' ', '_')}.png")

    cover.save(filename)

    print(f"✅ Cover saved to: {filename}")


# === MAIN ===

if __name__ == "__main__":

    print("๐Ÿ“š Generating random book cover...")

    # title = generate_book_title("Suggest a fantasy book title")

    title = generate_book_title()

    author = generate_author_name()


    print(f"Title: {title}")

    print(f"Author: {author}")


    generate_cover_image(title, author)


AI Chat Summarizer for WhatsApp

import re

import pandas as pd

import matplotlib.pyplot as plt

from textblob import TextBlob

from collections import Counter

from datetime import datetime

import os


# ========== CONFIG ==========

CHAT_FILE = "chat.txt"

PLOTS_FOLDER = "chat_analysis_plots"

os.makedirs(PLOTS_FOLDER, exist_ok=True)


# ========== 1. Parse WhatsApp Chat ==========

def parse_chat(file_path):

    with open(file_path, 'r', encoding='utf-8') as f:

        raw_text = f.readlines()


    messages = []

    pattern = r'^(\d{1,2}/\d{1,2}/\d{2,4}), (\d{1,2}:\d{2}) (AM|PM|am|pm)? - ([^:]+): (.*)'


    for line in raw_text:

        match = re.match(pattern, line)

        if match:

            date, time, am_pm, sender, message = match.groups()

            dt = datetime.strptime(date + " " + time + (" " + am_pm if am_pm else ""), "%d/%m/%Y %I:%M %p")

            messages.append([dt, sender.strip(), message.strip()])

    

    df = pd.DataFrame(messages, columns=["datetime", "sender", "message"])

    return df


# ========== 2. Sentiment & Stats ==========

def analyze_sentiments(df):

    df['polarity'] = df['message'].apply(lambda x: TextBlob(x).sentiment.polarity)

    df['sentiment'] = df['polarity'].apply(lambda x: 'positive' if x > 0.1 else 'negative' if x < -0.1 else 'neutral')

    return df


def top_senders(df, top_n=5):

    return df['sender'].value_counts().head(top_n)


# ========== 3. Plotting Functions ==========

def plot_message_frequency(df):

    df['date'] = df['datetime'].dt.date

    daily_counts = df.groupby('date').size()


    plt.figure(figsize=(12, 5))

    daily_counts.plot(kind='line', color='teal')

    plt.title("Messages Per Day")

    plt.xlabel("Date")

    plt.ylabel("Number of Messages")

    plt.tight_layout()

    plt.savefig(f"{PLOTS_FOLDER}/messages_per_day.png")

    plt.close()


def plot_sender_activity(df):

    sender_counts = df['sender'].value_counts()

    sender_counts.plot(kind='bar', figsize=(10,5), color='orchid')

    plt.title("Messages by Sender")

    plt.ylabel("Message Count")

    plt.tight_layout()

    plt.savefig(f"{PLOTS_FOLDER}/messages_by_sender.png")

    plt.close()


def plot_sentiment_distribution(df):

    sentiment_counts = df['sentiment'].value_counts()

    sentiment_counts.plot(kind='pie', autopct='%1.1f%%', figsize=(6,6), colors=['lightgreen', 'lightcoral', 'lightgrey'])

    plt.title("Sentiment Distribution")

    plt.tight_layout()

    plt.savefig(f"{PLOTS_FOLDER}/sentiment_distribution.png")

    plt.close()


# ========== 4. Generate Summary ==========

def generate_summary(df):

    summary = []

    summary.append(f"Total messages: {len(df)}")

    summary.append(f"Total participants: {df['sender'].nunique()}")

    summary.append("Top 5 active senders:")

    summary.extend(top_senders(df).to_string().split('\n'))


    sentiment_split = df['sentiment'].value_counts(normalize=True) * 100

    summary.append("\nSentiment Breakdown:")

    summary.extend(sentiment_split.round(2).to_string().split('\n'))


    with open("summary_output.txt", "w") as f:

        f.write("\n".join(summary))

    

    return "\n".join(summary)


# ========== MAIN ==========

if __name__ == "__main__":

    print("๐Ÿ“ฅ Parsing chat...")

    df = parse_chat(CHAT_FILE)


    print("๐Ÿง  Analyzing sentiments...")

    df = analyze_sentiments(df)


    print("๐Ÿ“Š Generating plots...")

    plot_message_frequency(df)

    plot_sender_activity(df)

    plot_sentiment_distribution(df)


    print("๐Ÿ“ Writing summary...")

    summary_text = generate_summary(df)

    print(summary_text)


    print("\n✅ Done! Plots saved to 'chat_analysis_plots' and summary to 'summary_output.txt'")