Sure, I can help you modify your code to use python-vlc for video playback to prevent the program from freezing when pressing the play buttons. Below is the updated code with the necessary changes.
Changes Made:
- Imported the
vlc module.
- Modified the
VideoPlayer class to use python-vlc instead of cv2 for video playback.
- Adjusted the
start_video and stop_video methods to use VLC player functions.
- Ensured that the video displays within the Tkinter application by embedding the VLC video output into a Tkinter widget.
Note: Embedding VLC video output into a Tkinter widget can be platform-specific. The following code provides a basic implementation that works on Windows and Linux. MacOS may require additional adjustments due to differences in the windowing system.
Here's the updated code:
import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import requests
import threading
import io
import os
import sys
import time
import vlc
# Video Player Class
class VideoPlayer:
def __init__(self, frame, video_path):
"""
:param frame: Tkinter Frame widget where the video will be displayed.
:param video_path: Path to the local video file.
"""
self.parent = frame
self.video_path = video_path
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
self.playing = False
def start_video(self):
if not self.video_path:
print("Video file path not specified.")
return
if self.playing:
return
media = self.instance.media_new(self.video_path)
self.player.set_media(media)
# Set the window where the video will be displayed
self.parent.update() # Ensure the Frame is realized
window_id = self.parent.winfo_id()
if sys.platform.startswith('win'):
self.player.set_hwnd(window_id)
elif sys.platform.startswith('linux'): # for Linux using the X Server
self.player.set_xwindow(window_id)
elif sys.platform == "darwin":
# Embedding on MacOS may require additional handling
print("Embedding video in Tkinter is not supported on MacOS in this example.")
# You may need to explore pyobjc or other methods for MacOS
else:
print("Unsupported platform for embedding video.")
# Start playing the video
self.player.play()
self.playing = True
def stop_video(self):
if self.playing:
self.player.stop()
self.playing = False
def release(self):
self.player.release()
self.instance.release()
# Video Download Function (Asynchronous)
def download_video(video_url, code, button):
if not video_url:
print(f"Video URL not found (Code: {code}).")
return
def download():
try:
response = requests.get(video_url, stream=True)
response.raise_for_status()
# Create 'videos' directory
if not os.path.exists('videos'):
os.makedirs('videos')
# File name using code
file_name = f"{code}.mp4"
save_path = os.path.join('videos', file_name)
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print(f"Video downloaded successfully: {save_path}")
# Change download button style to green
button.after(0, lambda: button.config(style='Green.TButton'))
except Exception as e:
print(f"Error downloading video (Code: {code}): {e}")
# Start download in a separate thread
threading.Thread(target=download, daemon=True).start()
# Data Fetch Function
def fetch_data(callback):
headers = {
'user-agent': 'Instagram 146.0.0.27.125 (iPhone12,1; iOS 13_3; en_US; en-US; scale=2.00; 1656x3584; 190542906)'
}
data = {
'target_user_id': '55408673825',
'page_size': '12'
}
try:
response = requests.post('https://i.instagram.com/api/v1/clips/user/', headers=headers, data=data)
response.raise_for_status()
response_data = response.json()
max_id = response_data['paging_info'].get('max_id')
print("Max ID:", max_id)
items = []
for i in range(len(response_data.get("items", []))):
try:
media = response_data["items"][i]["media"]
image_versions = media["image_versions2"]
candidates = image_versions.get("candidates", [])
if isinstance(candidates, list) and len(candidates) > 0:
candidates_frame = candidates[0].get("url")
if candidates_frame:
# Get Video URL
video_versions = media.get("video_versions", [])
if video_versions and isinstance(video_versions, list):
video_url = video_versions[0].get("url")
else:
video_url = None
# Get 'code' value
code = media.get("code", f"video_{i}")
items.append({
"image_url": candidates_frame,
"video_url": video_url,
"code": code
})
else:
candidates_frame = image_versions["candidates"]["url"]
video_versions = media.get("video_versions", [])
if video_versions and isinstance(video_versions, list):
video_url = video_versions[0].get("url")
else:
video_url = None
code = media.get("code", f"video_{i}")
items.append({
"image_url": candidates_frame,
"video_url": video_url,
"code": code
})
except (KeyError, IndexError, TypeError) as e:
print(f"Error retrieving data for item {i}:", e)
callback(items)
except Exception as e:
print("Error fetching data:", e)
callback([])
# Load Images Function
def load_images(items, frame, columns=3, image_size=(600, 900)):
def download_and_display(index, item):
image_url = item["image_url"]
video_url = item["video_url"]
code = item["code"]
try:
img_response = requests.get(image_url)
img_response.raise_for_status()
img_data = img_response.content
image = Image.open(io.BytesIO(img_data))
image = image.resize(image_size, Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(image)
def add_image():
row = (index // columns) * 2 # Every two rows (image + button)
col = index % columns
# Image Frame
image_frame = ttk.Frame(frame)
image_frame.grid(row=row, column=col, padx=5, pady=5)
# Video Display Frame
video_display_frame = tk.Frame(image_frame, width=image_size[0], height=image_size[1])
video_display_frame.pack()
# Configure the frame to have a fixed size
video_display_frame.pack_propagate(False)
# Image Label
label = tk.Label(video_display_frame, image=photo)
label.image = photo # Keep a reference
label.pack()
# Video Player
video_player = VideoPlayer(video_display_frame, os.path.join('videos', f"{code}.mp4"))
# Play Button
play_button = ttk.Button(image_frame, text="▶", width=3)
def toggle_video():
if video_player.playing:
video_player.stop_video()
# Reset the image
label.config(image=photo)
label.image = photo
play_button.config(text="▶")
else:
# Check if video file exists
video_file_path = os.path.join('videos', f"{code}.mp4")
if os.path.exists(video_file_path):
video_player.video_path = video_file_path
video_player.start_video()
play_button.config(text="■")
else:
messagebox.showinfo("Video Not Found", "Please download the video first.")
play_button.config(command=toggle_video)
play_button.place(relx=1.0, rely=0.0, anchor='ne')
# Download Button
if video_url:
download_button = ttk.Button(image_frame, text="Download",
command=lambda btn=None: download_video_button_action(video_url, code, download_button))
else:
download_button = ttk.Button(image_frame, text="Download", state="disabled")
download_button.pack(pady=5)
frame.after(0, add_image)
except Exception as e:
print(f"Error downloading image ({image_url}):", e)
def download_video_button_action(video_url, code, button):
download_video(video_url, code, button)
for idx, item in enumerate(items):
threading.Thread(target=download_and_display, args=(idx, item), daemon=True).start()
# Main Application Class
class ImageApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("Instagram Images")
self.state('zoomed') # Maximize window
self.bind("<F11>", self.toggle_fullscreen) # Toggle fullscreen with F11
self.bind("<Escape>", self.exit_fullscreen) # Exit fullscreen with Escape
# Style Definitions
self.style = ttk.Style()
self.style.configure('Green.TButton', foreground='white', background='#4CAF50')
self.style.map('Green.TButton',
foreground=[('active', 'white')],
background=[('active', '#45a049')])
# Scrollable Frame Setup
container = ttk.Frame(self)
container.pack(fill="both", expand=True)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
self.scrollable_frame = ttk.Frame(canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Enable mouse wheel scrolling
self.scrollable_frame.bind("<Enter>", lambda e: self.bind_mouse_wheel(canvas))
self.scrollable_frame.bind("<Leave>", lambda e: self.unbind_mouse_wheel(canvas))
# Loading Message
self.loading_label = ttk.Label(self.scrollable_frame, text="Loading images...", font=("Arial", 16))
self.loading_label.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
# Start data fetching
threading.Thread(target=self.start_fetching, daemon=True).start()
def bind_mouse_wheel(self, canvas):
if sys.platform.startswith('win'):
canvas.bind_all("<MouseWheel>", lambda event: self.on_mousewheel(event, canvas))
elif sys.platform.startswith('linux'):
canvas.bind_all("<Button-4>", lambda event: self.on_mousewheel(event, canvas))
canvas.bind_all("<Button-5>", lambda event: self.on_mousewheel(event, canvas))
def unbind_mouse_wheel(self, canvas):
if sys.platform.startswith('win'):
canvas.unbind_all("<MouseWheel>")
elif sys.platform.startswith('linux'):
canvas.unbind_all("<Button-4>")
canvas.unbind_all("<Button-5>")
def on_mousewheel(self, event, canvas):
if sys.platform.startswith('win'):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
elif sys.platform.startswith('linux'):
if event.num == 4:
canvas.yview_scroll(-1, "units")
elif event.num == 5:
canvas.yview_scroll(1, "units")
def toggle_fullscreen(self, event=None):
is_fullscreen = self.attributes("-fullscreen")
self.attributes("-fullscreen", not is_fullscreen)
def exit_fullscreen(self, event=None):
self.attributes("-fullscreen", False)
def start_fetching(self):
fetch_data(self.on_data_fetched)
def on_data_fetched(self, items):
# Remove loading message
self.scrollable_frame.after(0, self.loading_label.destroy)
# Load and display images
load_images(items, self.scrollable_frame)
if __name__ == "__main__":
app = ImageApp()
app.mainloop()
Explanation of Changes:
-
Importing vlc: We start by importing the vlc module to use the VLC media player functionalities.
-
Modifying VideoPlayer Class:
- Replaced the OpenCV-based video playback with
python-vlc.
- In
start_video, we create a new VLC media player instance and set the media to the video file.
- We retrieve the window ID of the Tkinter frame where the video should be displayed and set the VLC player's output to this window.
- Started the video playback using
self.player.play().
-
Embedding Video in Tkinter Frame:
- Instead of using a
Label for displaying the video, we now use a tk.Frame (video_display_frame) with a fixed size.
- The VLC player renders the video directly onto this frame.
- We pack an image label (
label) inside the frame for when the video is not playing.
- When the video starts, VLC takes over the frame and displays the video.
-
Handling Play/Pause Button:
- The
toggle_video function checks if the video file exists (expects the video to be downloaded first).
- If the video is playing, it stops the playback and resets the image.
- If the video is not playing and the file exists, it starts the playback.
-
Download Button:
- The download button allows the user to download the video.
- Once downloaded, the button changes style to indicate completion.
Additional Notes:
-
Platform Support:
- The embedding of VLC video output into a Tkinter widget is supported on Windows and Linux in this example.
- For MacOS, additional work may be required due to differences in the windowing system. The code includes a placeholder message for MacOS users.
-
Video Files:
- Videos are downloaded to the
videos directory with filenames based on their code.
- The video player looks for the corresponding video file in the
videos directory when attempting to play.
Dependencies:
Test the Updated Code:
- Run the script.
- Once the images load, click the "Download" button below an image to download the video.
- After downloading, click the play button (▶) to start the video playback within the application.
- Click the stop button (■) to stop the video and return to the image view.
By making these changes, the program should no longer freeze when pressing the play buttons, and the video playback is handled smoothly using python-vlc. The structure and functionality of your original code are preserved as much as possible.
Let me know if you have any questions or need further assistance!