if response.status_code == 200:
data = response.json()
video_url_hd = data['data'].get('hdplay', data['data']['play'])
video_title = data['data']['title']
sanitized_title = sanitize_title(video_title)
profile_name = data['data']['author']['unique_id']
profile_folder = os.path.join(save_location, profile_name)
os.makedirs(profile_folder, exist_ok=True)
download_with_progress(video_url_hd, sanitized_title, profile_folder)
else:
print(f"Failed to fetch video details for {link}: {response.status_code} - {response.text}")
except Exception as e:
print(f"An error occurred while downloading the video: {e}")
def download_with_progress(video_url, file_name, save_folder):
try:
print(f"Starting download: {file_name}")
with requests.get(video_url, stream=True) as response:
response.raise_for_status()
code
total_size_in_bytes = int(response.headers.get('content-length', 0))
block_size = 1024 # 1 Kilobyte
base_file_name = os.path.join(save_folder, f"{file_name}.mp4")
file_path = base_file_name
counter = 1
while os.path.exists(file_path):
file_path = os.path.join(save_folder, f"{file_name} {counter}.mp4")
counter += 1
with open(file_path, 'wb') as file:
downloaded_size = 0
# Initialize the progress update
print(f"Downloading {file_path} (0.00%)")
for data in response.iter_content(block_size):
downloaded_size += len(data)
file.write(data)
# Update progress in the console
if total_size_in_bytes > 0:
progress_percent = (downloaded_size / total_size_in_bytes) * 100
print(f"\rDownloading {file_path} ({progress_percent:.2f}%)", end='')
print(f"\nDownload completed: {file_path}")
except Exception as e:
print(f"An error occurred during download: {e}")
def show_download_complete_message():
# Ensure the QApplication instance exists
app = QApplication.instance() # Use the existing QApplication instance
if app is None:
app = QApplication(sys.argv) # Create a new QApplication instance if needed
msg_box = QMessageBox()
msg_box.setWindowTitle("Download") # Set the title of the message box
msg_box.setText("Download completed!") # Set the message text
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
links_str = sys.argv[1]
save_location = sys.argv[2]
# Split the links from the comma-separated string
links = links_str.split(',')
print(f"Links to download: {links}") # Debugging print
if not os.path.exists(save_location):
print(f"Error: Save location '{save_location}' does not exist.")
return
# Download each video link
for link in links:
print(f"Downloading video from link: {link}") # Debugging print
download_tiktok_video(link.strip(), save_location) # Ensure stripping any whitespace
# Show message box after all downloads are complete
show_download_complete_message()
os.system("title Downloading")
if name == 'main':
main()
Assistant
When converting a Python script that uses external libraries and subprocesses into an executable, there are several important considerations to keep in mind to ensure that everything works as expected. Here's a checklist and suggestions for troubleshooting your issue of conversion to .exe not working:
1. Using a Packaging Tool
Ensure you are using a suitable packaging tool like PyInstaller, cx_Freeze, or py2exe. For example, PyInstaller is commonly used and works well with PyQt5 apps.
If download_script.py is not included as a part of the executable, you need to ensure that both the main script and download_script.py are packaged together. You can do this by placing it in the same folder as the main script or using the --add-data option:
If you are running the app from an executable, check the logic in download_script.py. You may initialize a QApplication instance if you intend to use GUI components in it.
5. Test the Command Line Execution
After building the .exe, try running the download_script.exe directly from the command line to identify if there are error messages that could help you debug.
6. Set the Working Directory
Make sure that when you run your commands in subprocess, the current working directory is set correctly. You might need to set the cwd parameter in .
User
when i change command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location] and convert again. when i click download show popup one more program
Assistant
The behavior you described, where a new popup for another program appears when you press the "Download" button, suggests that the subprocess.Popen() command executed is launching another console window to run your download_script.py. This can happen when the script is executed as a separate process.
Solutions to Prevent Multiple Popups:
Use subprocess.run() Instead of subprocess.Popen():
If you only need to execute the command and wait for it to complete, consider using subprocess.run() instead. This prevents opening a new console window:
python
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
# Instead of Popen, use run
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
print("Error:", result.stderr) # Print any errors encountered
except Exception as e:
print(f"An error occurred: {e}")
Suppress Console Output:
If you still want to use subprocess.Popen, you can control whether or not to show a new console window. By using subprocess.STARTUPINFO like below, you can suppress the console window:
Make sure that download_script.py is functioning properly and does not include any GUI code unless that’s intended to display a message box or similar output.
When testing, be sure that your download_script.py does not itself inadvertently create additional window/pops as a result of operations (like showing a message box).
Final Thoughts:
By modifying your subprocess call to suppress new console windows or utilizing subprocess.run(), you should be able to run your download script without introducing new pop-ups. Test these changes to see which method best fits your needs. If you encounter further issues, please share any error messages or behaviors you observe, and I'll be glad to assist!
User
when i change command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location] and convert again. when i click download show popup one more program
This is should be open console
Assistant
If you want to run the separate download_script.py as a console application, opening a new console window is the expected behavior when using subprocess.Popen(). However, if it’s launching multiple console windows or behaving unexpectedly, here are some strategies to manage it properly while still achieving your desired effect:
1. Open a New Console Window Correctly
If your goal is to open a new console window explicitly for the download_script.py execution, confirm that you still want the subprocess.Popen() method with the appropriate flags set to show the console.
Here’s the code snippet to ensure the new console opens correctly:
python
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
# Start a new console process
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
2. Make Sure download_script.py is Designed to Run in a Console
Ensure that your download_script.py does not contain any GUI components that might trigger pop-up behavior inadvertently. If download_script.py uses PyQt5 for message boxes, you might see multiple windows if it runs multiple times.
3. Use subprocess.STARTUPINFO for Window Control
If you want to have control over how the windows behave, you can use subprocess.STARTUPINFO() to manage the startup options:
python
import subprocess
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # This ensures the window appears
# This will create a new console window
subprocess.Popen(command, startupinfo=startupinfo, creationflags=subprocess.CREATE_NEW_CONSOLE)
User
yntax error in D:\CA152\Test\Tiktok Downloader\video_downloader.py
File "D:\CA152\Test\Tiktok Downloader\video_downloader.py", line 85
def run_links_download(self, links, save_location):
Assistant
A SyntaxError in Python typically indicates that there is an issue with the structure of your code, which could be caused by several factors such as:
Unmatched parentheses or brackets
Incorrect indentation
Misspelled keywords or incorrect syntax
Since you provided the line number for the error (line 85), the problem is likely in or around that line. Let’s troubleshoot some common issues you might encounter:
1. Check for Syntax Errors Above Line 85
Often, the actual error may originate from code above the indicated line. Here’s what you should check:
Ensure that all functions and class definitions above line 85 are properly closed.
Look for any unmatched parentheses, brackets, or braces.
Ensure that all control structures (like if, for, while, etc.) are properly ended.
2. Check for Proper Indentation
Python is sensitive to indentation, and inconsistent use of spaces and tabs can lead to syntax errors. Ensure that you use either spaces or tabs consistently throughout your script. A common standard is to use 4 spaces for indentation.
3. Copy Relevant Code for Context
Without seeing the full structure of your code surrounding line 85, it’s hard to diagnose precisely. If possible, please share or check the relevant portion surrounding that line. Here’s an example of how it looks and what might be wrong before your function definition:
python
# Example snippet leading up to line 85
def some_other_function():
# ...
# Function defined before line 85
def another_function():
if True: # Ensure this is properly closed
return
# The line causing the issue
def run_links_download(self, links, save_location): # <-- Check this line and previous code
4. Missing or Misplaced Characters
Make sure there are no extra characters or missing colons (:) in the lines above. For example, "if" statements and function definitions should end with a colon.
5. Run Format Check
Use an IDE or code editor that highlights syntax issues, such as PyCharm, VSCode, or even simple linters like and .
User
full code for all please
Assistant
Sure! Below is the full code for both video_downloader.py and download_script.py, along with corrections and improvements that ensure proper functionality. I have formatted the code while preserving the original logic of your application.
video_downloader.py
python
User
I'm running video_downloader.py when i click download it show pop console status download but after convert click download become open one more tools?
Assistant
When you convert a script into an executable using tools like PyInstaller, you may notice different behaviors depending on how you've set up the subprocess calls. If the behavior changes from displaying a command line window with status messages during execution to opening another tool or program on download, this usually relates to how you're executing external scripts or processes in your code.
Understanding the Behavior
Normally, when you use subprocess.Popen with creationflags=subprocess.CREATE_NEW_CONSOLE, it opens a new terminal window where the command gets executed. This is useful if you want to see logs or output from your download_script.py.
If you're seeing the wrong window or an additional tool opens instead of the expected console output, try the following suggestions to troubleshoot:
Solutions
Check Path and Command Execution
Ensure your path and command are correct when invoking download_script.py. It should still point to the expected Python executable and correct script path. You can utilize os.path.abspath() to obtain the absolute path, which you've already done.
Use subprocess.run() for Immediate Execution
If you're okay with not having a separate console and wish to run the script and wait for it to complete, you can replace subprocess.Popen with subprocess.run(). This avoids the new window issue by executing the command inline.
python
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
# Use subprocess.run instead of Popen for immediate and inline execution
result = subprocess.run(command)
if result.returncode != 0:
print(f"Error occurred while running download_script.py: {result.stderr}")
Suppress Console Display Using Flags
If you want to keep using subprocess.Popen, but ensure it executes correctly while not showing unnecessary windows or using an incorrect executable, you can define a complete command through:
python
User
full code update
Assistant
Below is the updated full code for both video_downloader.py and download_script.py with modifications to address the issues you described. These changes should help ensure that the application runs as expected without introducing unwanted console windows and allows you to download TikTok videos properly.
video_downloader.py
This script contains a GUI for downloading TikTok videos. The download process is started by invoking the download_script.py using subprocess, with modifications to handle output correctly.
python
User
still same issue
Assistant
If you're still experiencing the issue where clicking "Download" opens up an unexpected window or tool instead of behaving as expected, let's troubleshoot the problem step-by-step and refine the implementation.
Things to Consider
Print Statements and Logging: Ensure that you have sufficient debug prints to trace what paths and parameters are being passed around. If your subprocess is not behaving as expected, it could be due to incorrect paths, missing files, or misinterpreted command-line arguments.
Command Line Behavior: When you run the executable, make sure you're running it directly from a command line (like CMD or PowerShell) to capture any output or error messages produced by the subprocess or the main application.
Recheck Your Environment: Ensure that the paths set for executables and scripts are accurate.
Refined Implementation
Let’s refine the code to enhance the debugging process and provide more control over the execution flow. I’ll also incorporate proper error handling to check if the script is callable and what exactly happens during execution:
Updated Code for video_downloader.py
Here’s an improved version of the GUI app that will log more information:
python
User
run with video_downloader.py still correct. but when convert still problem
Assistant
If the video_downloader.py script works correctly when run directly but encounters issues when converted to an executable with PyInstaller, the problem often lies in how PyInstaller handles dependencies, paths, or subprocess calls. Let's address this step by step to resolve the behavior you're experiencing when running the executable.
Steps to Troubleshoot and Fix the Executable Issue
Revisit the PyInstaller Command:
Make sure you are using the correct command to compile your script. Here’s the command you should use to build the executable:
--onefile: Packages everything into a single executable.
--windowed: Prevents opening a command prompt window when running the GUI.
--add-data: Ensures download_script.py is included in the build.
Refining the Command in the Executable:
Modify the subprocess call to ensure that the command can find download_script.py. You need to make sure it works with relative paths correctly when running as an executable:
python
import sys
import os
import subprocess
def run_links_download(self, links, save_location):
links_str = ','.join(links)
# Constructing plugin path correctly for executable
if hasattr(sys, '_MEIPASS'):
# If running as a packaged executable
script_path = os.path.join(sys._MEIPASS, "download_script.py")
else:
# If running as a normal script
script_path = os.path.abspath("download_script.py")
command = [sys.executable, script_path, links_str, save_location]
print(f"Running command: {command}") # Debugging print
try:
# Open a new console for the subprocess
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
except Exception as e:
print(f"Failed to start download_script: {e}")
User
full code
Assistant
Certainly! Below is the full code for both video_downloader.py and download_script.py, updated with the necessary modifications to handle execution as an executable with PyInstaller.
video_downloader.py
This script is your main GUI for downloading TikTok videos. It constructs the command to call the download script and ensures that it finds the necessary files regardless of whether it is being run as a standalone script or as an executable.
After building your executable, run it via command line to observe any missing dependencies. If your application fails due to missing modules, PyInstaller can sometimes miss them.
8. Include Console Output for Debugging
If you're not already doing so, ensure your subprocess command is set up to capture output or prints, so you can see if there are any errors.
Example Command with Debugging
Here’s an example for modification in video_downloader.py:
For more complex applications, consider creating a .spec file, which allows you to fine-tune the build process.
Conclusion
Once you've made the necessary changes, rebuild your executable with PyInstaller or your chosen tool. Run your executable from the command line to check for any errors. Debugging is often easiest when you can see console output directly. If issues persist, feel free to ask for any specific error messages you receive!
4. Debug and Test from Command Line
To determine how your scripts behave when called as expected, execute the download_script.py directly from the command line to see if errors occur that might lead to multiple pop-ups.
If your download_script.py shows a message box when a download is complete, make sure it runs only once and handles downloads properly without invoking multiple message boxes for subsequent requests.
6. Confirm Each Download Call
Ensure that your methods don’t redundantly call the download script. For example, before you add each link, check to avoid duplicates, or ensure the logic in your start_download() method does not execute multiple times unintentionally.
Conclusion
By carefully reviewing your method for launching download_script.py and ensuring that it is only invoked under the correct circumstances, you can achieve the desired effect of opening a console without unwanted duplicates or multiple console windows. If problems persist, please let me know what specific behavior you're experiencing (for example, “two pop-ups instead of one”), and we can explore further troubleshooting steps!
flake8
pylint
Example Code Block
Here’s how a typical section of your video_downloader.py might look; make sure yours follows a similar structure:
python
class VideoDownloaderApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
# Function calls and definitions properly closed
def initUI(self):
# Initialization code here
pass
def run_links_download(self, links, save_location):
# Code logic here
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
Conclusion
If you review the code for indentation and structure, focusing on the lines leading up to line 85, you should be able to identify the syntax error. If you're still having trouble, feel free to share more context (like the few lines before line 85), and I can provide more precise help!
import sys
import subprocess
import os
import urllib.parse
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton,
QTextEdit, QLabel, QLineEdit, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt
class VideoDownloaderApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('TikTok Video Downloader')
self.setGeometry(100, 100, 400, 400)
self.setStyleSheet("background-color: #e0f7fa;") # Light blue background
layout = QVBoxLayout()
# Title label
title_label = QLabel('TikTok Video Downloader')
title_label.setAlignment(Qt.AlignCenter)
title_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #00796b;")
layout.addWidget(title_label)
# Link input area
self.link_input = QTextEdit(self)
self.link_input.setPlaceholderText("Enter TikTok Links (one per line) or paths to links.txt files:")
self.link_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.link_input)
# Save folder input
self.save_path_input = QLineEdit(self)
self.save_path_input.setPlaceholderText("Save Folder:")
self.save_path_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.save_path_input)
# Browse button
browse_button = QPushButton('Browse', self)
browse_button.clicked.connect(self.browse_folder)
browse_button.setStyleSheet("background-color: #00796b; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
layout.addWidget(browse_button)
# Download button
self.download_button = QPushButton('Download', self)
self.download_button.clicked.connect(self.start_download)
self.update_download_button_state() # Initial state
layout.addWidget(self.download_button)
self.link_input.textChanged.connect(self.update_download_button_state) # Update button state on text change
self.save_path_input.textChanged.connect(self.update_download_button_state) # Update button state on save path change
self.setLayout(layout)
def browse_folder(self):
folder = QFileDialog.getExistingDirectory(self, 'Select Save Folder')
if folder:
self.save_path_input.setText(folder)
def start_download(self):
save_location = self.save_path_input.text()
links_input = self.link_input.toPlainText().strip()
if links_input and save_location:
links = []
txt_files = []
for line in links_input.splitlines():
line = line.strip()
if line:
if line.endswith('.txt'):
txt_files.append(line)
else:
links.append(line)
# Start console processes for links
if links:
self.run_links_download(links, save_location)
# Start console processes for each .txt file
for file_path in txt_files:
self.run_file_download(file_path, save_location)
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
def run_file_download(self, file_path, save_location):
links = self.get_links_from_file(file_path)
if links:
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
print(f"No valid links found in {file_path}")
def get_links_from_file(self, file_path):
if file_path.startswith("file:///"):
file_path = urllib.parse.unquote(file_path[8:])
links = []
try:
with open(file_path, 'r') as file:
links = [link.strip() for link in file.readlines() if link.strip()]
print(f"Links read from {file_path}: {links}")
except Exception as e:
print(f"Error reading links from file: {e}")
return links
def update_download_button_state(self):
links_input = self.link_input.toPlainText().strip()
save_location = self.save_path_input.text().strip()
if links_input and save_location:
self.download_button.setStyleSheet("background-color: #388e3c; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
else:
self.download_button.setStyleSheet("background-color: #a0a0a0; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = VideoDownloaderApp()
window.show()
sys.exit(app.exec_())
download_script.py
python
import sys
import os
import re
import requests
from PyQt5.QtWidgets import QApplication, QMessageBox
def sanitize_title(title):
return re.sub(r'[\/:*?"<>|]', '', title)
def download_tiktok_video(link, save_location):
try:
print(f"Fetching video details for: {link}")
api_url = "https://www.tikwm.com/api/"
params = {"url": link}
response = requests.get(api_url, params=params)
if response.status_code == 200:
data = response.json()
video_url_hd = data['data'].get('hdplay', data['data']['play'])
video_title = data['data']['title']
sanitized_title = sanitize_title(video_title)
profile_name = data['data']['author']['unique_id']
profile_folder = os.path.join(save_location, profile_name)
os.makedirs(profile_folder, exist_ok=True)
download_with_progress(video_url_hd, sanitized_title, profile_folder)
else:
print(f"Failed to fetch video details for {link}: {response.status_code} - {response.text}")
except Exception as e:
print(f"An error occurred while downloading the video: {e}")
def download_with_progress(video_url, file_name, save_folder):
try:
print(f"Starting download: {file_name}")
with requests.get(video_url, stream=True) as response:
response.raise_for_status()
total_size_in_bytes = int(response.headers.get('content-length', 0))
block_size = 1024 # 1 Kilobyte
base_file_name = os.path.join(save_folder, f"{file_name}.mp4")
file_path = base_file_name
counter = 1
while os.path.exists(file_path):
file_path = os.path.join(save_folder, f"{file_name} {counter}.mp4")
counter += 1
with open(file_path, 'wb') as file:
downloaded_size = 0
# Initialize the progress update
print(f"Downloading {file_path} (0.00%)")
for data in response.iter_content(block_size):
downloaded_size += len(data)
file.write(data)
# Update progress in the console
if total_size_in_bytes > 0:
progress_percent = (downloaded_size / total_size_in_bytes) * 100
print(f"\rDownloading {file_path} ({progress_percent:.2f}%)", end='')
print(f"\nDownload completed: {file_path}")
except Exception as e:
print(f"An error occurred during download: {e}")
def show_download_complete_message():
app = QApplication.instance() # Use the existing QApplication instance if available
if app is None:
app = QApplication(sys.argv) # Create a new QApplication instance if needed
msg_box = QMessageBox()
msg_box.setWindowTitle("Download") # Set the title of the message box
msg_box.setText("Download completed!") # Set the message text
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
def main():
if len(sys.argv) != 3:
print("Usage: python download_script.py <links_comma_separated> <save_location>")
return
links_str = sys.argv[1]
save_location = sys.argv[2]
# Split the links from the comma-separated string
links = links_str.split(',')
print(f"Links to download: {links}") # Debugging print
if not os.path.exists(save_location):
print(f"Error: Save location '{save_location}' does not exist.")
return
# Download each video link
for link in links:
print(f"Downloading video from link: {link}") # Debugging print
download_tiktok_video(link.strip(), save_location) # Ensure stripping any whitespace
# Show message box after all downloads are complete
show_download_complete_message()
if __name__ == '__main__':
main()
Key Changes and Improvements:
Console Control: Using sys.executable to ensure Python runs, and using os.path.abspath() to ensure the path is correct.
Consistent Indentation: Ensure that all code maintains consistent indentation (four spaces in this case).
Checks Before Running: Ensures that the save_location directory exists before starting downloads.
Error Handling: Improved error messages for better debugging.
How to Use:
Save both scripts to the same folder.
Ensure you have all the required packages installed:
bash
pip install PyQt5 requests
Run video_downloader.py. This GUI app allows you to input TikTok links and download videos by executing download_script.py for each link.
Compiling to .exe:
When you're ready to compile your application using a tool like PyInstaller, remember to ensure both scripts are included and that you handle the windowing as necessary. For example:
If you run into any issues with this code, questions, or need further adjustments, feel free to ask!
import subprocess
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
# Ensure it opens in a new console properly
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # Suppressing the console window creation flag
process = subprocess.Popen(command, startupinfo=startupinfo)
process.wait() # Wait for the process to complete (if needed)
Debugging the Executable and Path Issues
Run your executable from a command line/terminal. This way, you can see any errors or outputs that may be suppressed. If your script behaves differently when executed from an IDE, that may indicate the working directory or paths are resolved differently.
Ensure download_script.py Completes Properly
Ensure that download_script.py doesn't inadvertently trigger other applications or scripts. If it's calling an external tool for downloading (via API or script), make sure the API you're connecting to has not changed.
Compiling with PyInstaller
If you haven’t done so, ensure you compile your video_downloader.py properly:
--windowed prevents console windows from appearing when launching the GUI application.
--onefile compiles everything into a single executable.
Final Note
Try some of these adjustments and observe how they affect the behavior when you execute the application. If you still encounter issues, please include specific error messages or behaviors so I can assist you more effectively!
import sys
import subprocess
import os
import urllib.parse
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton,
QTextEdit, QLabel, QLineEdit, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt
class VideoDownloaderApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('TikTok Video Downloader')
self.setGeometry(100, 100, 400, 400)
self.setStyleSheet("background-color: #e0f7fa;") # Light blue background
layout = QVBoxLayout()
# Title label
title_label = QLabel('TikTok Video Downloader')
title_label.setAlignment(Qt.AlignCenter)
title_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #00796b;")
layout.addWidget(title_label)
# Link input area
self.link_input = QTextEdit(self)
self.link_input.setPlaceholderText("Enter TikTok Links (one per line) or paths to links.txt files:")
self.link_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.link_input)
# Save folder input
self.save_path_input = QLineEdit(self)
self.save_path_input.setPlaceholderText("Save Folder:")
self.save_path_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.save_path_input)
# Browse button
browse_button = QPushButton('Browse', self)
browse_button.clicked.connect(self.browse_folder)
browse_button.setStyleSheet("background-color: #00796b; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
layout.addWidget(browse_button)
# Download button
self.download_button = QPushButton('Download', self)
self.download_button.clicked.connect(self.start_download)
self.update_download_button_state() # Initial state
layout.addWidget(self.download_button)
self.link_input.textChanged.connect(self.update_download_button_state) # Update button state on text change
self.save_path_input.textChanged.connect(self.update_download_button_state) # Update button state on save path change
self.setLayout(layout)
def browse_folder(self):
folder = QFileDialog.getExistingDirectory(self, 'Select Save Folder')
if folder:
self.save_path_input.setText(folder)
def start_download(self):
save_location = self.save_path_input.text()
links_input = self.link_input.toPlainText().strip()
if links_input and save_location:
links = []
txt_files = []
for line in links_input.splitlines():
line = line.strip()
if line:
if line.endswith('.txt'):
txt_files.append(line)
else:
links.append(line)
# Start console processes for links
if links:
self.run_links_download(links, save_location)
# Start console processes for each .txt file
for file_path in txt_files:
self.run_file_download(file_path, save_location)
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
# Using subprocess.Popen to open a new console
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
def run_file_download(self, file_path, save_location):
links = self.get_links_from_file(file_path)
if links:
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
# Using subprocess.Popen to open a new console for each file
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
print(f"No valid links found in {file_path}")
def get_links_from_file(self, file_path):
if file_path.startswith("file:///"):
file_path = urllib.parse.unquote(file_path[8:])
links = []
try:
with open(file_path, 'r') as file:
links = [link.strip() for link in file.readlines() if link.strip()]
print(f"Links read from {file_path}: {links}")
except Exception as e:
print(f"Error reading links from file: {e}")
return links
def update_download_button_state(self):
links_input = self.link_input.toPlainText().strip()
save_location = self.save_path_input.text().strip()
if links_input and save_location:
self.download_button.setStyleSheet("background-color: #388e3c; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
else:
self.download_button.setStyleSheet("background-color: #a0a0a0; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = VideoDownloaderApp()
window.show()
sys.exit(app.exec_())
download_script.py
This script handles the video downloading based on the links provided by the GUI. It ensures that download progress is displayed correctly.
python
import sys
import os
import re
import requests
from PyQt5.QtWidgets import QApplication, QMessageBox
def sanitize_title(title):
return re.sub(r'[\/:*?"<>|]', '', title)
def download_tiktok_video(link, save_location):
try:
print(f"Fetching video details for: {link}")
api_url = "https://www.tikwm.com/api/"
params = {"url": link}
response = requests.get(api_url, params=params)
if response.status_code == 200:
data = response.json()
video_url_hd = data['data'].get('hdplay', data['data']['play'])
video_title = data['data']['title']
sanitized_title = sanitize_title(video_title)
profile_name = data['data']['author']['unique_id']
profile_folder = os.path.join(save_location, profile_name)
os.makedirs(profile_folder, exist_ok=True)
download_with_progress(video_url_hd, sanitized_title, profile_folder)
else:
print(f"Failed to fetch video details for {link}: {response.status_code} - {response.text}")
except Exception as e:
print(f"An error occurred while downloading the video: {e}")
def download_with_progress(video_url, file_name, save_folder):
try:
print(f"Starting download: {file_name}")
with requests.get(video_url, stream=True) as response:
response.raise_for_status()
total_size_in_bytes = int(response.headers.get('content-length', 0))
block_size = 1024 # 1 Kilobyte
base_file_name = os.path.join(save_folder, f"{file_name}.mp4")
file_path = base_file_name
counter = 1
while os.path.exists(file_path):
file_path = os.path.join(save_folder, f"{file_name} {counter}.mp4")
counter += 1
with open(file_path, 'wb') as file:
downloaded_size = 0
# Initialize the progress update
print(f"Downloading {file_path} (0.00%)")
for data in response.iter_content(block_size):
downloaded_size += len(data)
file.write(data)
# Update progress in the console
if total_size_in_bytes > 0:
progress_percent = (downloaded_size / total_size_in_bytes) * 100
print(f"\rDownloading {file_path} ({progress_percent:.2f}%)", end='')
print(f"\nDownload completed: {file_path}")
except Exception as e:
print(f"An error occurred during download: {e}")
def show_download_complete_message():
app = QApplication.instance() # Use the existing QApplication instance if available
if app is None:
app = QApplication(sys.argv) # Create a new QApplication instance if needed
msg_box = QMessageBox()
msg_box.setWindowTitle("Download") # Set the title of the message box
msg_box.setText("Download completed!") # Set the message text
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
def main():
if len(sys.argv) != 3:
print("Usage: python download_script.py <links_comma_separated> <save_location>")
return
links_str = sys.argv[1]
save_location = sys.argv[2]
# Split the links from the comma-separated string
links = links_str.split(',')
print(f"Links to download: {links}") # Debugging print
if not os.path.exists(save_location):
print(f"Error: Save location '{save_location}' does not exist.")
return
# Download each video link
for link in links:
print(f"Downloading video from link: {link}") # Debugging print
download_tiktok_video(link.strip(), save_location) # Ensure stripping any whitespace
# Show message box after all downloads are complete
show_download_complete_message()
if __name__ == '__main__':
main()
Key Considerations
Console Window Management:
The subprocess commands are designed to open a new console window to show logs and errors from the download_script.py when it is executed.
User Feedback:
The application will provide real-time feedback in the console about the download status and will show a message when the download is complete.
File Management:
The downloader creates a separate folder for each TikTok user based on their unique ID in the specified save location.
Compiling to .exe
When converting the above code into a standalone executable using PyInstaller, use the command:
This command will bundle both scripts into one executable file. The --windowed option will suppress the console window for the main application but will still open new console windows for download_script.py.
Final Steps
Ensure you test the application functionally, checking that links properly download and the console appropriately indicates the process.
If further issues arise or if you need adjustments, feel free to ask!
import sys
import subprocess
import os
import urllib.parse
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton,
QTextEdit, QLabel, QLineEdit, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt
class VideoDownloaderApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('TikTok Video Downloader')
self.setGeometry(100, 100, 400, 400)
self.setStyleSheet("background-color: #e0f7fa;") # Light blue background
layout = QVBoxLayout()
# Title label
title_label = QLabel('TikTok Video Downloader')
title_label.setAlignment(Qt.AlignCenter)
title_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #00796b;")
layout.addWidget(title_label)
# Link input area
self.link_input = QTextEdit(self)
self.link_input.setPlaceholderText("Enter TikTok Links:")
self.link_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.link_input)
# Save folder input
self.save_path_input = QLineEdit(self)
self.save_path_input.setPlaceholderText("Save Folder:")
self.save_path_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.save_path_input)
# Browse button
browse_button = QPushButton('Browse', self)
browse_button.clicked.connect(self.browse_folder)
browse_button.setStyleSheet("background-color: #00796b; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
layout.addWidget(browse_button)
# Download button
self.download_button = QPushButton('Download', self)
self.download_button.clicked.connect(self.start_download)
self.update_download_button_state() # Initial state
layout.addWidget(self.download_button)
self.link_input.textChanged.connect(self.update_download_button_state)
self.save_path_input.textChanged.connect(self.update_download_button_state)
self.setLayout(layout)
def browse_folder(self):
folder = QFileDialog.getExistingDirectory(self, 'Select Save Folder')
if folder:
self.save_path_input.setText(folder)
def start_download(self):
save_location = self.save_path_input.text()
links_input = self.link_input.toPlainText().strip()
if links_input and save_location:
links = [link.strip() for link in links_input.splitlines() if link.strip()]
self.run_links_download(links, save_location)
def run_links_download(self, links, save_location):
links_str = ','.join(links)
command = [sys.executable, os.path.abspath("download_script.py"), links_str, save_location]
print(f"Running command: {command}") # Debugging print
try:
# Open a new console for the subprocess
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
except Exception as e:
print(f"Failed to start download_script: {e}")
def update_download_button_state(self):
links_input = self.link_input.toPlainText().strip()
save_location = self.save_path_input.text().strip()
if links_input and save_location:
self.download_button.setStyleSheet("background-color: #388e3c; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
else:
self.download_button.setStyleSheet("background-color: #a0a0a0; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = VideoDownloaderApp()
window.show()
sys.exit(app.exec_())
Updated Code for download_script.py
Make sure download_script.py continues to work correctly. Here’s an enhanced version:
python
import sys
import os
import re
import requests
from PyQt5.QtWidgets import QApplication, QMessageBox
def sanitize_title(title):
return re.sub(r'[\/:*?"<>|]', '', title)
def download_tiktok_video(link, save_location):
try:
print(f"Fetching video details for: {link}")
api_url = "https://www.tikwm.com/api/"
params = {"url": link}
response = requests.get(api_url, params=params)
if response.status_code == 200:
data = response.json()
video_url_hd = data['data'].get('hdplay', data['data']['play'])
video_title = data['data']['title']
sanitized_title = sanitize_title(video_title)
profile_name = data['data']['author']['unique_id']
profile_folder = os.path.join(save_location, profile_name)
os.makedirs(profile_folder, exist_ok=True)
download_with_progress(video_url_hd, sanitized_title, profile_folder)
else:
print(f"Failed to fetch video details for {link}: {response.status_code} - {response.text}")
except Exception as e:
print(f"An error occurred while downloading the video: {e}")
def download_with_progress(video_url, file_name, save_folder):
try:
print(f"Starting download: {file_name}")
with requests.get(video_url, stream=True) as response:
response.raise_for_status()
total_size_in_bytes = int(response.headers.get('content-length', 0))
block_size = 1024 # 1 Kilobyte
base_file_name = os.path.join(save_folder, f"{file_name}.mp4")
file_path = base_file_name
counter = 1
while os.path.exists(file_path):
file_path = os.path.join(save_folder, f"{file_name} {counter}.mp4")
counter += 1
with open(file_path, 'wb') as file:
downloaded_size = 0
# Initialize the progress update
print(f"Downloading {file_path} (0.00%)")
for data in response.iter_content(block_size):
downloaded_size += len(data)
file.write(data)
if total_size_in_bytes > 0:
progress_percent = (downloaded_size / total_size_in_bytes) * 100
print(f"\rDownloading {file_path} ({progress_percent:.2f}%)", end='')
print(f"\nDownload completed: {file_path}")
except Exception as e:
print(f"An error occurred during download: {e}")
def show_download_complete_message():
app = QApplication.instance() # Use the existing QApplication instance if available
if app is None:
app = QApplication(sys.argv) # Create a new QApplication instance if needed
msg_box = QMessageBox()
msg_box.setWindowTitle("Download")
msg_box.setText("Download completed!")
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
def main():
if len(sys.argv) != 3:
print("Usage: python download_script.py <links_comma_separated> <save_location>")
return
links_str = sys.argv[1]
save_location = sys.argv[2]
# Split the links into a list
links = links_str.split(',')
print(f"Links to download: {links}") # Debugging print
if not os.path.exists(save_location):
print(f"Error: Save location '{save_location}' does not exist.")
return
# Download each video link
for link in links:
print(f"Downloading video from link: {link.strip()}") # Debugging print
download_tiktok_video(link.strip(), save_location) # Ensure stripping any whitespace
# Show message box after all downloads are complete
show_download_complete_message()
if __name__ == '__main__':
main()
Detailed Steps to Test the Functionality
Run from Command Line: If you haven’t already, run your video_downloader.py directly from the command line to capture any output or errors that appear in the console. This can provide valuable insights into what might go wrong.
Check Console Outputs: Ensure the prints for commands show as expected. They will help verify:
The paths to scripts are being resolved correctly.
If there are any exceptions or error messages from running the script.
Verify Executable: After compiling into an executable with PyInstaller:
then navigate to the generated dist folder and execute the newly created .exe file from the command line.
Check Path Issues: If the path to download_script.py or other resources is unclear or misrepresented, modify the print statements with os.path.abspath() to track down the correct paths being used.
Ensure Correct Python Environment: Make sure the correct Python environment or installation has access to requests and PyQt5. You may have issues if you try to run the executable where certain packages are missing.
Further Diagnosis
If issues persist, please provide specifics on what happens when you hit "Download" (e.g., are there error messages, does it open a new console, etc.)? This information will help narrow down possible reasons for the strange behavior.
Including Module Paths:
The if hasattr(sys, '_MEIPASS'): check is crucial. When PyInstaller packages your script, it stores external files in a temporary folder when running as an executable. This check ensures that download_script.py is found at runtime.
Run the Executable from a Command Prompt:
To see if there are any console errors or output, run the generated .exe file from a command line window:
bash
cd dist
video_downloader.exe
This way, you can observe any errors or outputs that can help you diagnose the issue further.
Testing the Executable
After implementing these changes, recompile your application and test it again:
Recompile with PyInstaller.
Run the resulting executable from the command line and check for console prints/errors.
Common Problems and Considerations
Missing Dependencies: Ensure that both download_script.py and requests, PyQt5 libraries are correctly routed and included.
Path Issues: Relative paths versus absolute paths should be handled carefully, especially in executables.
Environment Conflicts: Sometimes the environment in which you run the .exe can differ from that in the IDE or your command line, leading to issues.
Conclusion
Following the above steps and modifications should help you build a working executable version of your TikTok downloader. If you continue to face issues, please provide any specific error messages or unexpected behavior you observe, and we’ll dig deeper into the problem.
import sys
import subprocess
import os
import urllib.parse
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton,
QTextEdit, QLabel, QLineEdit, QFileDialog, QMessageBox)
from PyQt5.QtCore import Qt
class VideoDownloaderApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('TikTok Video Downloader')
self.setGeometry(100, 100, 400, 400)
self.setStyleSheet("background-color: #e0f7fa;") # Light blue background
layout = QVBoxLayout()
# Title label
title_label = QLabel('TikTok Video Downloader')
title_label.setAlignment(Qt.AlignCenter)
title_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #00796b;")
layout.addWidget(title_label)
# Link input area
self.link_input = QTextEdit(self)
self.link_input.setPlaceholderText("Enter TikTok Links:")
self.link_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.link_input)
# Save folder input
self.save_path_input = QLineEdit(self)
self.save_path_input.setPlaceholderText("Save Folder:")
self.save_path_input.setStyleSheet("font-size: 12px; border: 1px solid #00796b; border-radius: 5px;")
layout.addWidget(self.save_path_input)
# Browse button
browse_button = QPushButton('Browse', self)
browse_button.clicked.connect(self.browse_folder)
browse_button.setStyleSheet("background-color: #00796b; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
layout.addWidget(browse_button)
# Download button
self.download_button = QPushButton('Download', self)
self.download_button.clicked.connect(self.start_download)
self.update_download_button_state() # Initial state
layout.addWidget(self.download_button)
self.link_input.textChanged.connect(self.update_download_button_state)
self.save_path_input.textChanged.connect(self.update_download_button_state)
self.setLayout(layout)
def browse_folder(self):
folder = QFileDialog.getExistingDirectory(self, 'Select Save Folder')
if folder:
self.save_path_input.setText(folder)
def start_download(self):
save_location = self.save_path_input.text()
links_input = self.link_input.toPlainText().strip()
if links_input and save_location:
links = [link.strip() for link in links_input.splitlines() if link.strip()]
self.run_links_download(links, save_location)
def run_links_download(self, links, save_location):
links_str = ','.join(links)
# Determine the path for download_script.py
if hasattr(sys, '_MEIPASS'):
# If running as a packaged executable
script_path = os.path.join(sys._MEIPASS, "download_script.py")
else:
# If running as a normal script
script_path = os.path.abspath("download_script.py")
command = [sys.executable, script_path, links_str, save_location]
print(f"Running command: {command}") # Debugging print
try:
# Open a new console for the subprocess
subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
except Exception as e:
print(f"Failed to start download_script: {e}")
def update_download_button_state(self):
links_input = self.link_input.toPlainText().strip()
save_location = self.save_path_input.text().strip()
if links_input and save_location:
self.download_button.setStyleSheet("background-color: #388e3c; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
else:
self.download_button.setStyleSheet("background-color: #a0a0a0; color: white; font-weight: bold; padding: 10px; border-radius: 5px;")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = VideoDownloaderApp()
window.show()
sys.exit(app.exec_())
download_script.py
This script handles the actual downloading of the videos based on the TikTok links provided.
python
import sys
import os
import re
import requests
from PyQt5.QtWidgets import QApplication, QMessageBox
def sanitize_title(title):
return re.sub(r'[\/:*?"<>|]', '', title)
def download_tiktok_video(link, save_location):
try:
print(f"Fetching video details for: {link}")
api_url = "https://www.tikwm.com/api/"
params = {"url": link}
response = requests.get(api_url, params=params)
if response.status_code == 200:
data = response.json()
video_url_hd = data['data'].get('hdplay', data['data']['play'])
video_title = data['data']['title']
sanitized_title = sanitize_title(video_title)
profile_name = data['data']['author']['unique_id']
profile_folder = os.path.join(save_location, profile_name)
os.makedirs(profile_folder, exist_ok=True)
download_with_progress(video_url_hd, sanitized_title, profile_folder)
else:
print(f"Failed to fetch video details for {link}: {response.status_code} - {response.text}")
except Exception as e:
print(f"An error occurred while downloading the video: {e}")
def download_with_progress(video_url, file_name, save_folder):
try:
print(f"Starting download: {file_name}")
with requests.get(video_url, stream=True) as response:
response.raise_for_status()
total_size_in_bytes = int(response.headers.get('content-length', 0))
block_size = 1024 # 1 Kilobyte
base_file_name = os.path.join(save_folder, f"{file_name}.mp4")
file_path = base_file_name
counter = 1
while os.path.exists(file_path):
file_path = os.path.join(save_folder, f"{file_name} {counter}.mp4")
counter += 1
with open(file_path, 'wb') as file:
downloaded_size = 0
# Initialize the progress update
print(f"Downloading {file_path} (0.00%)")
for data in response.iter_content(block_size):
downloaded_size += len(data)
file.write(data)
if total_size_in_bytes > 0:
progress_percent = (downloaded_size / total_size_in_bytes) * 100
print(f"\rDownloading {file_path} ({progress_percent:.2f}%)", end='')
print(f"\nDownload completed: {file_path}")
except Exception as e:
print(f"An error occurred during download: {e}")
def show_download_complete_message():
app = QApplication.instance() # Use the existing QApplication instance if available
if app is None:
app = QApplication(sys.argv) # Create a new QApplication instance if needed
msg_box = QMessageBox()
msg_box.setWindowTitle("Download")
msg_box.setText("Download completed!")
msg_box.setStandardButtons(QMessageBox.Ok)
msg_box.exec_()
def main():
if len(sys.argv) != 3:
print("Usage: python download_script.py <links_comma_separated> <save_location>")
return
links_str = sys.argv[1]
save_location = sys.argv[2]
# Split the links into a list
links = links_str.split(',')
print(f"Links to download: {links}") # Debugging print
if not os.path.exists(save_location):
print(f"Error: Save location '{save_location}' does not exist.")
return
# Download each video link
for link in links:
print(f"Downloading video from link: {link.strip()}") # Debugging print
download_tiktok_video(link.strip(), save_location)
# Show message box after all downloads are complete
show_download_complete_message()
if __name__ == '__main__':
main()
Important Notes:
Path Handling:
The video_downloader.py uses a conditional to check if it’s running as a packaged executable to find the path to download_script.py. This will ensure it works correctly whether you're running it in a development environment or as a compiled executable.
User Interface:
The GUI allows you to input TikTok links either directly or via a text file and to specify a save location for the downloaded videos.
Compiling with PyInstaller:
To create the executable, use the following command:
This command compiles your main script and includes the download script in the build.
Final Steps
Compile the Application: Follow the steps to create the executable using PyInstaller.
Test the Executable: Run the compiled .exe from a command prompt to observe any outputs or errors.
Monitor for Errors: If unexpected behavior occurs, check your console for any debug prints which can be useful for diagnosing issues.
By following these instructions and using the provided code, you should be able to create a functional TikTok downloader application. If any issues persist during execution or building the application, please share the specific symptoms or error messages for further assistance.