Guest User

Untitled

a guest
Mar 27th, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.46 KB | None | 0 0
  1. import tkinter as tk
  2. from tkinter import filedialog, messagebox, colorchooser
  3. from PIL import Image, ImageDraw, ImageFont, ImageTk
  4. from moviepy.editor import VideoFileClip
  5. import random
  6.  
  7. # Function to generate a random caption
  8. def generate_caption():
  9. captions = [
  10. "Feeling adventurous today! 🌟 #AdventureTime #ExploreMore",
  11. "Lazy Sundays are the best! 😴 #LazyDay #ChillVibes",
  12. "New week, new goals! 💪 #MondayMotivation #GoalGetter",
  13. "Life is better with friends! 👯‍♀️ #FriendshipGoals #Besties",
  14. "Good vibes only! ✨ #PositiveVibes #GoodEnergy"
  15. ]
  16. return random.choice(captions)
  17.  
  18. # Function to select hashtags based on the caption
  19. def select_hashtags(caption):
  20. # Define a dictionary of hashtags for different categories
  21. hashtags_dict = {
  22. "adventure": ["#AdventureTime", "#ExploreMore", "#Wanderlust"],
  23. "relaxation": ["#LazyDay", "#ChillVibes", "#RelaxAndUnwind"],
  24. "motivation": ["#MondayMotivation", "#GoalGetter", "#DreamBig"],
  25. "friendship": ["#FriendshipGoals", "#Besties", "#SquadGoals"],
  26. "positivity": ["#PositiveVibes", "#GoodEnergy", "#SpreadLove"]
  27. }
  28.  
  29. # Select hashtags based on keywords present in the caption
  30. selected_hashtags = []
  31. for category, hashtags in hashtags_dict.items():
  32. if category in caption.lower():
  33. selected_hashtags.extend(hashtags)
  34.  
  35. # Return up to three selected hashtags
  36. return selected_hashtags[:3]
  37.  
  38. # Function to handle button click event for media selection
  39. def select_media():
  40. media_type = media_type_var.get()
  41. if media_type == "image":
  42. file_path = filedialog.askopenfilename(initialdir="/", title="Select Image", filetypes=(("Image files", "*.jpg;*.jpeg;*.png"), ("All files", "*.*")))
  43. elif media_type == "video":
  44. file_path = filedialog.askopenfilename(initialdir="/", title="Select Video", filetypes=(("Video files", "*.mp4;*.avi;*.mov"), ("All files", "*.*")))
  45. media_path_var.set(file_path)
  46.  
  47. # Function to generate an Instagram post
  48. def generate_instagram_post(media_path, caption, font_style, text_color):
  49. # Open the media file
  50. try:
  51. if media_path.endswith(('.jpg', '.jpeg', '.png')):
  52. media = Image.open(media_path)
  53. elif media_path.endswith(('.mp4', '.avi', '.mov')):
  54. clip = VideoFileClip(media_path)
  55. frame = clip.get_frame(0) # Extract the first frame from the video
  56. media = Image.fromarray(frame)
  57. else:
  58. raise ValueError("Unsupported media file format.")
  59.  
  60. # Convert image to RGB mode if it has an alpha channel
  61. if media.mode == "RGBA":
  62. media = media.convert("RGB")
  63.  
  64. # Create a drawing context
  65. draw = ImageDraw.Draw(media)
  66.  
  67. # Define text parameters
  68. font = ImageFont.truetype(font_style, 30)
  69. text_position = (50, 50)
  70.  
  71. # Add caption text to the image
  72. draw.text(text_position, caption, fill=text_color, font=font)
  73.  
  74. # Save the modified image
  75. media.save("generated_post.jpg")
  76. messagebox.showinfo("Success", "Instagram post generated successfully!")
  77. except Exception as e:
  78. messagebox.showerror("Error", str(e))
  79.  
  80. # Function to handle button click event for post generation
  81. def generate_post():
  82. # Get media type and file path from radio buttons and entry widgets
  83. media_type = media_type_var.get()
  84. media_path = media_path_var.get()
  85.  
  86. # Get font style and text color
  87. font_style = font_style_var.get()
  88. text_color = text_color_var.get()
  89.  
  90. # Generate a random caption
  91. caption = generate_caption()
  92.  
  93. # Generate hashtags based on the caption
  94. hashtags = select_hashtags(caption)
  95.  
  96. # Update the caption with selected hashtags
  97. caption_with_hashtags = f"{caption} {' '.join(hashtags)}"
  98.  
  99. # Generate the Instagram post
  100. generate_instagram_post(media_path, caption_with_hashtags, font_style, text_color)
  101.  
  102. # Function to select text color
  103. def select_text_color():
  104. color = colorchooser.askcolor(title="Select Text Color")
  105. text_color_var.set(color[1])
  106.  
  107. # Function to display a preview of the generated post
  108. def preview_post():
  109. # Get media type and file path from radio buttons and entry widgets
  110. media_type = media_type_var.get()
  111. media_path = media_path_var.get()
  112.  
  113. # Get font style and text color
  114. font_style = font_style_var.get()
  115. text_color = text_color_var.get()
  116.  
  117. # Generate a random caption
  118. caption = generate_caption()
  119.  
  120. # Generate hashtags based on the caption
  121. hashtags = select_hashtags(caption)
  122.  
  123. # Update the caption with selected hashtags
  124. caption_with_hashtags = f"{caption} {' '.join(hashtags)}"
  125.  
  126. # Generate a preview of the Instagram post
  127. try:
  128. #
  129. # Open the media file
  130. if media_path.endswith(('.jpg', '.jpeg', '.png')):
  131. media = Image.open(media_path)
  132. elif media_path.endswith(('.mp4', '.avi', '.mov')):
  133. clip = VideoFileClip(media_path)
  134. frame = clip.get_frame(0) # Extract the first frame from the video
  135. media = Image.fromarray(frame)
  136. else:
  137. raise ValueError("Unsupported media file format.")
  138.  
  139. # Convert image to RGB mode if it has an alpha channel
  140. if media.mode == "RGBA":
  141. media = media.convert("RGB")
  142.  
  143. # Create a drawing context
  144. draw = ImageDraw.Draw(media)
  145.  
  146. # Define text parameters
  147. font = ImageFont.truetype(font_style, 30)
  148. text_position = (50, 50)
  149.  
  150. # Add caption text to the image
  151. draw.text(text_position, caption_with_hashtags, fill=text_color, font=font)
  152.  
  153. # Display the preview in a separate window
  154. preview_window = tk.Toplevel(root)
  155. preview_window.title("Instagram Post Preview")
  156.  
  157. # Convert the PIL image to a Tkinter PhotoImage
  158. photo_image = ImageTk.PhotoImage(media)
  159.  
  160. # Display the image in a label
  161. image_label = tk.Label(preview_window, image=photo_image)
  162. image_label.image = photo_image # Keep a reference to prevent garbage collection
  163. image_label.pack()
  164. except Exception as e:
  165. messagebox.showerror("Error", str(e))
  166.  
  167. # Create the main window
  168. root = tk.Tk()
  169. root.title("Instagram Post Generator")
  170.  
  171. # Set the width and height of the GUI window
  172. root.geometry("600x400")
  173.  
  174. # Create radio buttons for selecting image or video
  175. media_type_var = tk.StringVar()
  176. tk.Label(root, text="Select Media Type:").pack()
  177. tk.Radiobutton(root, text="Image", variable=media_type_var, value="image").pack()
  178. tk.Radiobutton(root, text="Video", variable=media_type_var, value="video").pack()
  179.  
  180. # Create a button to select media (image or video)
  181. select_media_button = tk.Button(root, text="Select Media", command=select_media)
  182. select_media_button.pack()
  183.  
  184. # Create labels and entry widgets for file path
  185. tk.Label(root, text="File Path:").pack()
  186. media_path_var = tk.StringVar()
  187. media_path_entry = tk.Entry(root, textvariable=media_path_var, width=50)
  188. media_path_entry.pack()
  189.  
  190. # Create labels and entry widgets for font style and text color
  191. tk.Label(root, text="Font Style:").pack()
  192. font_style_var = tk.StringVar()
  193. font_style_var.set("arial.ttf") # Default font style
  194. font_style_entry = tk.Entry(root, textvariable=font_style_var, width=50)
  195. font_style_entry.pack()
  196.  
  197. tk.Label(root, text="Text Color:").pack()
  198. text_color_var = tk.StringVar()
  199. text_color_var.set("#000000") # Default text color (black)
  200. text_color_entry = tk.Entry(root, textvariable=text_color_var, width=50)
  201. text_color_entry.pack()
  202.  
  203. # Create buttons to select font style and text color
  204. select_font_style_button = tk.Button(root, text="Select Font Style", command=lambda: font_style_var.set(filedialog.askopenfilename(initialdir="/", title="Select Font Style")))
  205. select_font_style_button.pack()
  206.  
  207. select_text_color_button = tk.Button(root, text="Select Text Color", command=select_text_color)
  208. select_text_color_button.pack()
  209.  
  210. # Create a button to generate the post
  211. generate_button = tk.Button(root, text="Generate Post", command=generate_post)
  212. generate_button.pack()
  213.  
  214. # Create a button to preview the post
  215. preview_button = tk.Button(root, text="Preview Post", command=preview_post)
  216. preview_button.pack()
  217.  
  218. # Run the Tkinter event loop
  219. root.mainloop()
  220.  
  221.  
  222.  
Advertisement
Add Comment
Please, Sign In to add comment