https://v.douyin.com/iMDjRYda/
1. Download Google Chrome
Just Baidu it and download the latest version: https://www.google.cn/chrome/
2. Create a Google Chrome shortcut
Create a Google Chrome shortcut for dedicated script use.
Method: Right-click the desktop, then choose Create shortcut, select the EXE file in your Chrome root directory, then enter it in the following format and click OK when done. Double-click to open.
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --start-maximized --disable-images
3. Manual port startup method
If a new browser cannot be opened, start it manually in CMD (remember to replace it with your Chrome installation path)
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir="C:\path\to\user\data" --start-maximized --disable-images
4. Open this shortcut
Do not close it; all subsequent operations will be visualized in this browser.
5. Script introduction and configuration changes
(1) Monitor videos on specified authors' homepages; you can configure multiple authors and replace them yourself at the end of the script.
- You can control the monitoring cycle time. The default is to check once every hour. As long as the script is not closed, it will keep monitoring.
- You can control the number of videos downloaded.
- You can control how recently the videos to download must have been published.
(2) Use the OpenAI speech model API to recognize the audio script and convert it into a text file.
(3) Submit the content of the text file to the API again, then control the secondary creation through prompts. By then, you can write a good set yourself.
Each author will become a separate folder. The folder contains a videos folder and a script folder for easy management.
Note that because the OpenAI API is used, you need to enable a VPN before use and replace it with your own API.
Specific script
```python
import datetime
import time
import os
import openai
import moviepy.editor as mp
from DrissionPage import ChromiumPage, ChromiumOptions
# 设置OpenAI API密钥
openai.api_key = 'sk-proj-fwfwfwffwefwefwefwefwef这里换成你自己的API'
def print_msg(msg):
print(f'[{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] {msg}')
def init_page_and_tabs():
print_msg("Initializing browser options...")
co = ChromiumOptions(read_file=False)
co.use_system_user_path(on_off=True)
co.set_local_port(9222)
co.set_argument('--remote-debugging-port=9222')
co.set_argument('--start-maximized')
co.set_argument('--disable-images')
co.set_argument('--headless=new') # 如果需要无界面浏览器
co.set_argument('--no-sandbox') # 如果在Linux系统上运行
co.set_timeouts(30, 30, 30)
co.set_retry(5, 5)
print_msg("Browser options configured.")
p = ChromiumPage(addr_or_opts=co)
return p
def open_author_page(tab, author_url):
print_msg(f"Opening Douyin author page: {author_url}")
tab.get(author_url)
tab.wait(5)
current_url = tab.url
print_msg(f"Current URL: {current_url}")
def download_video(tab, aweme_id, video_url, author_folder):
path = os.path.join(author_folder, "videos")
if not os.path.exists(path):
os.makedirs(path)
print_msg(f"Downloading video {aweme_id}.mp4 from {video_url}")
d_r = tab.download(file_url=video_url, rename=aweme_id, suffix='mp4', goal_path=path, file_exists='overwrite')
if d_r[0] == 'success':
print_msg(f'视频 {aweme_id}.mp4 下载成功')
return os.path.join(path, f"{aweme_id}.mp4")
else:
print_msg(f'下载视频 {aweme_id}.mp4 失败')
return None
def extract_audio_from_video(video_path, audio_path):
try:
video = mp.VideoFileClip(video_path)
video.audio.write_audiofile(audio_path)
except Exception as e:
print(f"Error extracting audio from {video_path}: {e}")
def transcribe_audio(audio_path):
try:
with open(audio_path, 'rb') as audio_file:
response = openai.Audio.transcribe(
model="whisper-1",
file=audio_file
)
return response['text']
except Exception as e:
print(f"Error transcribing audio {audio_path}: {e}")
return None
def secondary_creation(transcription, prompt="Please make some pseudo-original contributions to the script for this video, but don't overdo it or stray from the original meaning. If it's the lyrics, please don't make any changes.", temperature=0):
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a creative writer."},
{"role": "user", "content": f"{prompt}\n\n{transcription}"},
],
temperature=temperature
)
return response.choices[0].message['content']
except Exception as e:
print(f"Error in secondary creation: {e}")
return None
def process_video_for_transcription(video_path, author_folder):
output_folder = os.path.join(author_folder, 'transcriptions')
if not os.path.exists(output_folder):
os.makedirs(output_folder)
audio_path = os.path.join(output_folder, f"{os.path.splitext(os.path.basename(video_path))[0]}.wav")
transcript_path = os.path.join(output_folder, f"{os.path.splitext(os.path.basename(video_path))[0]}.txt")
secondary_transcript_path = os.path.join(output_folder, f"{os.path.splitext(os.path.basename(video_path))[0]}_secondary.txt")
print(f"Processing {video_path}...")
extract_audio_from_video(video_path, audio_path)
transcription = transcribe_audio(audio_path)
if transcription:
with open(transcript_path, 'w', encoding='utf-8') as transcript_file:
transcript_file.write(transcription)
print(f"Transcription saved to {transcript_path}")
secondary_transcription = secondary_creation(transcription, temperature=0.5)
if secondary_transcription:
with open(secondary_transcript_path, 'w', encoding='utf-8') as secondary_file:
secondary_file.write(secondary_transcription)
print(f"Secondary transcription saved to {secondary_transcript_path}")
# 删除临时音频文件
if os.path.exists(audio_path):
os.remove(audio_path)
def loop_function(tab, author_url, author_folder):
open_author_page(tab, author_url)
print_msg("Starting loop function...")
api_url = 'https://www.douyin.com/aweme/v1/web/aweme/post/'
tab.listen.start(api_url)
tab.refresh()
res = tab.listen.wait(timeout=30)
tab.listen.stop()
if res:
print_msg(f"Response received: {res.response}")
if not res.is_failed:
if isinstance(res.response.body, dict):
try:
aweme_list = res.response.body.get("aweme_list", [])[:10] # 只检查前10个视频
print_msg(f"Found {len(aweme_list)} videos")
current_time = int(time.time())
for dic in aweme_list:
create_time = dic['create_time']
aweme_id = dic['aweme_id']
media_type = dic['media_type']
create_datetime = datetime.datetime.fromtimestamp(create_time)
print_msg(f"Checking video {aweme_id} created at {create_datetime} (current time: {datetime.datetime.now()})")
if (current_time - create_time) <= 86400 and aweme_id not in posted_list and media_type == 4:
video_url = dic['video']['play_addr']['url_list'][0]
print_msg(f"New video found: {aweme_id}, downloading...")
video_path = download_video(tab, aweme_id, video_url, author_folder)
if video_path:
process_video_for_transcription(video_path, author_folder)
posted_list.append(aweme_id)
else:
print_msg(f"Skipping video {aweme_id} (either older than 24 hours or already processed)")
except KeyError:
print_msg("The key 'aweme_list' does not exist in the dictionary")
else:
print_msg("The response body is not a dictionary")
else:
print_msg("Failed to get response")
else:
print_msg("Waited for 30 seconds but no response was received")
if __name__ == '__main__':
print_msg("Script started.")
page = init_page_and_tabs()
posted_list = [] # 初始化已处理过的视频列表
# 作者列表
authors = [
'https://www.douyin.com/user/MS4wLjABAAAAVbCB1A3LQqVLrrnP1Hk0cN6ray_Y2u8L060Ki4oXcJW7gelwcATaiRS8l6ZuwIWp?vid=7392646110654762240',
'https://www.douyin.com/user/MS4wLjABAAAA3Ur7oScCtfrA_vyn7p6k9TkcOaYlMpjZ7N92kfbyKRY?vid=7391735731858705674'
]
while True:
for idx, author_url in enumerate(authors, start=1):
author_folder = os.path.join(os.getcwd(), f"author_{idx}")
if not os.path.exists(author_folder):
os.makedirs(author_folder)
tab_douyin = page.new_tab()
print_msg(f"Starting new check cycle for author {idx}: {author_url}")
loop_function(tab_douyin, author_url, author_folder)
print_msg(f"Check complete for author {idx}: {author_url}. Sleeping for 1 minute before next author.")
time.sleep(60) # 每个作者之间间隔1分钟
print_msg("All authors checked. Sleeping for 1 hour before next cycle.")
time.sleep(3600 - 60 * len(authors)) # 减去中间的等待时间,确保总的周期为1小时
``` |