Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from tkinter import filedialog, messagebox, colorchooser
- from PIL import Image, ImageDraw, ImageFont, ImageTk
- from moviepy.editor import VideoFileClip
- import random
- # Function to generate a random caption
- def generate_caption():
- captions = [
- "Feeling adventurous today! 🌟 #AdventureTime #ExploreMore",
- "Lazy Sundays are the best! 😴 #LazyDay #ChillVibes",
- "New week, new goals! 💪 #MondayMotivation #GoalGetter",
- "Life is better with friends! 👯♀️ #FriendshipGoals #Besties",
- "Good vibes only! ✨ #PositiveVibes #GoodEnergy"
- ]
- return random.choice(captions)
- # Function to select hashtags based on the caption
- def select_hashtags(caption):
- # Define a dictionary of hashtags for different categories
- hashtags_dict = {
- "adventure": ["#AdventureTime", "#ExploreMore", "#Wanderlust"],
- "relaxation": ["#LazyDay", "#ChillVibes", "#RelaxAndUnwind"],
- "motivation": ["#MondayMotivation", "#GoalGetter", "#DreamBig"],
- "friendship": ["#FriendshipGoals", "#Besties", "#SquadGoals"],
- "positivity": ["#PositiveVibes", "#GoodEnergy", "#SpreadLove"]
- }
- # Select hashtags based on keywords present in the caption
- selected_hashtags = []
- for category, hashtags in hashtags_dict.items():
- if category in caption.lower():
- selected_hashtags.extend(hashtags)
- # Return up to three selected hashtags
- return selected_hashtags[:3]
- # Function to handle button click event for media selection
- def select_media():
- media_type = media_type_var.get()
- if media_type == "image":
- file_path = filedialog.askopenfilename(initialdir="/", title="Select Image", filetypes=(("Image files", "*.jpg;*.jpeg;*.png"), ("All files", "*.*")))
- elif media_type == "video":
- file_path = filedialog.askopenfilename(initialdir="/", title="Select Video", filetypes=(("Video files", "*.mp4;*.avi;*.mov"), ("All files", "*.*")))
- media_path_var.set(file_path)
- # Function to generate an Instagram post
- def generate_instagram_post(media_path, caption, font_style, text_color):
- # Open the media file
- try:
- if media_path.endswith(('.jpg', '.jpeg', '.png')):
- media = Image.open(media_path)
- elif media_path.endswith(('.mp4', '.avi', '.mov')):
- clip = VideoFileClip(media_path)
- frame = clip.get_frame(0) # Extract the first frame from the video
- media = Image.fromarray(frame)
- else:
- raise ValueError("Unsupported media file format.")
- # Convert image to RGB mode if it has an alpha channel
- if media.mode == "RGBA":
- media = media.convert("RGB")
- # Create a drawing context
- draw = ImageDraw.Draw(media)
- # Define text parameters
- font = ImageFont.truetype(font_style, 30)
- text_position = (50, 50)
- # Add caption text to the image
- draw.text(text_position, caption, fill=text_color, font=font)
- # Save the modified image
- media.save("generated_post.jpg")
- messagebox.showinfo("Success", "Instagram post generated successfully!")
- except Exception as e:
- messagebox.showerror("Error", str(e))
- # Function to handle button click event for post generation
- def generate_post():
- # Get media type and file path from radio buttons and entry widgets
- media_type = media_type_var.get()
- media_path = media_path_var.get()
- # Get font style and text color
- font_style = font_style_var.get()
- text_color = text_color_var.get()
- # Generate a random caption
- caption = generate_caption()
- # Generate hashtags based on the caption
- hashtags = select_hashtags(caption)
- # Update the caption with selected hashtags
- caption_with_hashtags = f"{caption} {' '.join(hashtags)}"
- # Generate the Instagram post
- generate_instagram_post(media_path, caption_with_hashtags, font_style, text_color)
- # Function to select text color
- def select_text_color():
- color = colorchooser.askcolor(title="Select Text Color")
- text_color_var.set(color[1])
- # Function to display a preview of the generated post
- def preview_post():
- # Get media type and file path from radio buttons and entry widgets
- media_type = media_type_var.get()
- media_path = media_path_var.get()
- # Get font style and text color
- font_style = font_style_var.get()
- text_color = text_color_var.get()
- # Generate a random caption
- caption = generate_caption()
- # Generate hashtags based on the caption
- hashtags = select_hashtags(caption)
- # Update the caption with selected hashtags
- caption_with_hashtags = f"{caption} {' '.join(hashtags)}"
- # Generate a preview of the Instagram post
- try:
- #
- # Open the media file
- if media_path.endswith(('.jpg', '.jpeg', '.png')):
- media = Image.open(media_path)
- elif media_path.endswith(('.mp4', '.avi', '.mov')):
- clip = VideoFileClip(media_path)
- frame = clip.get_frame(0) # Extract the first frame from the video
- media = Image.fromarray(frame)
- else:
- raise ValueError("Unsupported media file format.")
- # Convert image to RGB mode if it has an alpha channel
- if media.mode == "RGBA":
- media = media.convert("RGB")
- # Create a drawing context
- draw = ImageDraw.Draw(media)
- # Define text parameters
- font = ImageFont.truetype(font_style, 30)
- text_position = (50, 50)
- # Add caption text to the image
- draw.text(text_position, caption_with_hashtags, fill=text_color, font=font)
- # Display the preview in a separate window
- preview_window = tk.Toplevel(root)
- preview_window.title("Instagram Post Preview")
- # Convert the PIL image to a Tkinter PhotoImage
- photo_image = ImageTk.PhotoImage(media)
- # Display the image in a label
- image_label = tk.Label(preview_window, image=photo_image)
- image_label.image = photo_image # Keep a reference to prevent garbage collection
- image_label.pack()
- except Exception as e:
- messagebox.showerror("Error", str(e))
- # Create the main window
- root = tk.Tk()
- root.title("Instagram Post Generator")
- # Set the width and height of the GUI window
- root.geometry("600x400")
- # Create radio buttons for selecting image or video
- media_type_var = tk.StringVar()
- tk.Label(root, text="Select Media Type:").pack()
- tk.Radiobutton(root, text="Image", variable=media_type_var, value="image").pack()
- tk.Radiobutton(root, text="Video", variable=media_type_var, value="video").pack()
- # Create a button to select media (image or video)
- select_media_button = tk.Button(root, text="Select Media", command=select_media)
- select_media_button.pack()
- # Create labels and entry widgets for file path
- tk.Label(root, text="File Path:").pack()
- media_path_var = tk.StringVar()
- media_path_entry = tk.Entry(root, textvariable=media_path_var, width=50)
- media_path_entry.pack()
- # Create labels and entry widgets for font style and text color
- tk.Label(root, text="Font Style:").pack()
- font_style_var = tk.StringVar()
- font_style_var.set("arial.ttf") # Default font style
- font_style_entry = tk.Entry(root, textvariable=font_style_var, width=50)
- font_style_entry.pack()
- tk.Label(root, text="Text Color:").pack()
- text_color_var = tk.StringVar()
- text_color_var.set("#000000") # Default text color (black)
- text_color_entry = tk.Entry(root, textvariable=text_color_var, width=50)
- text_color_entry.pack()
- # Create buttons to select font style and text color
- select_font_style_button = tk.Button(root, text="Select Font Style", command=lambda: font_style_var.set(filedialog.askopenfilename(initialdir="/", title="Select Font Style")))
- select_font_style_button.pack()
- select_text_color_button = tk.Button(root, text="Select Text Color", command=select_text_color)
- select_text_color_button.pack()
- # Create a button to generate the post
- generate_button = tk.Button(root, text="Generate Post", command=generate_post)
- generate_button.pack()
- # Create a button to preview the post
- preview_button = tk.Button(root, text="Preview Post", command=preview_post)
- preview_button.pack()
- # Run the Tkinter event loop
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment