It appears you're encountering errors related to multithreading/multiprocessing while processing video frames, specifically:
2024-10-07 10:58:09,074 [ERROR] Error processing frame: 'NoneType' object has no attribute 'get'
...
The error suggests that somewhere in your process_single_frame function or within the RenderModel, a NoneType object is being accessed improperly. Multithreading or multiprocessing can sometimes introduce complexities that make debugging more challenging, especially if objects or resources aren't being shared correctly between processes.
Given your request "不要视频多线程" ("Do not use multithreading for video"), I'll provide a revised version of your script that processes video frames sequentially without using ProcessPoolExecutor. This should help eliminate the concurrency-related issues and make debugging easier.
Revised Script Without Multithreading/Multiprocessing
Here's the modified script with multiprocessing removed. The frames will be processed one by one in a single thread.
import os
import sys
import uuid
import re
import shutil
import subprocess
import logging
import wave
import cv2
import numpy as np
import tqdm
import time
from talkingface.audio_model import AudioModel
from talkingface.render_model import RenderModel
from piper.voice import PiperVoice
# =============================================================
# Setup Logging
# =============================================================
logging.basicConfig(
level=logging.INFO, # Set to INFO for general logs
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.FileHandler("processing_optimized.log"),
logging.StreamHandler(sys.stdout)
]
)
# =============================================================
# Helper Functions
# =============================================================
def preprocess_text(text):
"""
Preprocess the input text by removing specific patterns and non-ASCII characters.
"""
logging.info("Original Text: %s", text)
text = re.sub(r'~+', '!', text)
text = re.sub(r"\(.*?\)", "", text)
text = re.sub(r"(\*[^*]+\*)|(_[^_]+_)", "", text).strip()
text = re.sub(r'[^\x00-\x7F]+', '', text)
logging.info("Preprocessed Text: %s", text)
return text
def synthesize_audio(voice, text, output_wav_path):
"""
Synthesize speech from text and save it to a WAV file.
"""
try:
with wave.open(output_wav_path, 'w') as wav_file:
voice.synthesize(preprocess_text(text), wav_file)
logging.info(f"Audio synthesized and saved to {output_wav_path}")
except Exception as e:
logging.error(f"Audio synthesis failed: {e}")
sys.exit(1)
def convert_audio(input_wav, output_wav):
"""
Convert audio to the desired format using FFmpeg.
"""
try:
subprocess.run([
"ffmpeg", "-y", # Overwrite output files without asking
"-i", input_wav, # Input file
"-ar", "16000", # Set audio sampling rate to 16000 Hz
output_wav # Output file
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
logging.info(f"Audio converted and saved to {output_wav}")
except subprocess.CalledProcessError as e:
logging.error(f"Audio conversion failed: {e.stderr.decode().strip()}")
sys.exit(1)
def merge_audio_video(save_path, wavpath, output_video_name):
"""
Merge processed video and audio into the final output video using FFmpeg.
"""
try:
subprocess.run([
"ffmpeg", "-y", # Overwrite output files without asking
"-i", save_path, # Input video
"-i", wavpath, # Input audio
"-c:v", "libx264", # Video codec
"-pix_fmt", "yuv420p", # Pixel format
"-c:a", "aac", # Audio codec
"-strict", "experimental", # Allow experimental codecs
output_video_name # Output file
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
logging.info(f"Audio and video merged into {output_video_name}")
except subprocess.CalledProcessError as e:
logging.error(f"Merging audio and video failed: {e.stderr.decode().strip()}")
sys.exit(1)
def process_single_frame(frame, render_model):
"""
Process a single video frame using the RenderModel.
"""
try:
processed_frame = render_model.interface(frame)
if processed_frame is None:
logging.warning("Processed frame is None. Using a blank frame.")
processed_frame = np.ones_like(frame) * 255 # White frame as placeholder
return processed_frame
except Exception as e:
logging.error(f"Error processing frame: {e}")
return np.ones_like(frame) * 255 # White frame as placeholder
def read_video_properties(video_path):
"""
Read video properties such as width and height.
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
logging.error(f"Unable to open video: {video_path}")
sys.exit(1)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.release()
logging.info(f"Video properties - Width: {width}, Height: {height}")
return width, height
# =============================================================
# Main Function
# =============================================================
def main():
# Initialize Models within the main process
try:
model = "en_US-john-medium.onnx"
voice = PiperVoice.load(model)
logging.info("PiperVoice model loaded successfully.")
except Exception as e:
logging.error(f"Failed to load PiperVoice model: {e}")
sys.exit(1)
try:
audioModel = AudioModel()
audioModel.loadModel("checkpoint/audio.pkl")
logging.info("AudioModel loaded successfully.")
except Exception as e:
logging.error(f"Failed to load AudioModel: {e}")
sys.exit(1)
try:
renderModel = RenderModel()
renderModel.loadModel("checkpoint/render.pth")
logging.info("RenderModel loaded successfully.")
except Exception as e:
logging.error(f"Failed to load RenderModel: {e}")
sys.exit(1)
print("=====================")
# Define paths and filenames
filename = 'temp.wav'
text = '''Gunman lurked for hours before Trump's last-minute game of golf
4 hours ago
Madeline Halpert
BBC News
Reporting from
West Palm Beach, Florida
Bodycam footage shows arrest of suspected Trump gunman
”'''
# Synthesize audio
synthesize_audio(voice, text, filename)
# Get command-line arguments
try:
video_path_input = sys.argv[1]
print(f"Video path is set to: {video_path_input}")
audio_path = filename
print(f"Audio path is set to: {audio_path}")
output_video_name = sys.argv[3]
print(f"Output video name is set to: {output_video_name}")
except IndexError:
logging.error("Insufficient command-line arguments provided.")
logging.error("Usage: python demo.py <video_input_path> <unused_arg> <output_video_name>")
sys.exit(1)
# Define paths
pkl_path = os.path.join(video_path_input, "keypoint_rotate.pkl")
video_path_processed = os.path.join(video_path_input, "circle.mp4")
if not os.path.exists(pkl_path):
logging.error(f"Keypoint pickle file not found at {pkl_path}")
sys.exit(1)
if not os.path.exists(video_path_processed):
logging.error(f"Processed video file not found at {video_path_processed}")
sys.exit(1)
# Reset character in RenderModel within the main process
try:
renderModel.reset_charactor(video_path_processed, pkl_path)
logging.info("RenderModel.reset_charactor completed successfully.")
except Exception as e:
logging.error(f"Failed to reset character: {e}")
sys.exit(1)
# Convert audio using subprocess.run
wavpath = 'output_audio1.wav'
try:
subprocess.run([
"ffmpeg", "-y", # Overwrite output files without asking
"-i", audio_path, # Input file
"-ar", "16000", # Set audio sampling rate to 16000 Hz
wavpath # Output file
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
logging.info(f"Audio converted and saved to {wavpath}")
except subprocess.CalledProcessError as e:
logging.error(f"Audio conversion failed: {e.stderr.decode().strip()}")
sys.exit(1)
# Generate mouth frames from audio
try:
mouth_frame = audioModel.interface_wav(wavpath)
# Proper validation to avoid ambiguous truth value error
if isinstance(mouth_frame, np.ndarray):
if mouth_frame.size == 0:
logging.error("Mouth frame generation returned no frames.")
sys.exit(1)
elif isinstance(mouth_frame, (list, tuple)):
if len(mouth_frame) == 0:
logging.error("Mouth frame generation returned no frames.")
sys.exit(1)
else:
logging.error("Unexpected type for mouth_frame. It should be a list, tuple, or NumPy array.")
sys.exit(1)
logging.info(f"Generated {len(mouth_frame)} mouth frames from audio.")
except Exception as e:
logging.error(f"Failed to generate mouth frames: {e}")
sys.exit(1)
# Read video properties
vid_width, vid_height = read_video_properties(video_path_processed)
# Prepare output directory and VideoWriter
task_id = str(uuid.uuid1())
output_dir = os.path.join("output", task_id)
os.makedirs(output_dir, exist_ok=True)
save_path = os.path.join(output_dir, "silence.mp4")
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
try:
videoWriter = cv2.VideoWriter(save_path, fourcc, 25, (vid_width, vid_height))
if not videoWriter.isOpened():
logging.error(f"Failed to initialize VideoWriter with path: {save_path}")
sys.exit(1)
logging.info(f"VideoWriter initialized with save path: {save_path}")
except Exception as e:
logging.error(f"Failed to initialize VideoWriter: {e}")
sys.exit(1)
# Process frames sequentially
start_time = time.time()
try:
logging.info("Starting frame processing sequentially.")
for idx, frame in enumerate(tqdm.tqdm(mouth_frame, desc="Processing Frames")):
processed_frame = process_single_frame(frame, renderModel)
videoWriter.write(processed_frame)
except Exception as e:
logging.error(f"Failed during frame processing: {e}")
videoWriter.release()
shutil.rmtree(output_dir)
sys.exit(1)
videoWriter.release()
elapsed_time = time.time() - start_time
logging.info(f"Frame processing completed in {elapsed_time:.2f} seconds.")
# Merge audio and video
try:
merge_audio_video(save_path, wavpath, output_video_name)
except Exception as e:
logging.error(f"Failed to merge audio and video: {e}")
shutil.rmtree(output_dir)
sys.exit(1)
# Clean up temporary files and directories
try:
shutil.rmtree(output_dir)
logging.info(f"Cleaned up temporary directory: {output_dir}")
except Exception as e:
logging.warning(f"Failed to remove temporary directory {output_dir}: {e}")
# Remove temporary audio files
try:
os.remove(wavpath)
os.remove(audio_path)
logging.info("Temporary audio files removed.")
except Exception as e:
logging.warning(f"Failed to remove temporary audio files: {e}")
logging.info(f"Output video saved to {os.path.abspath(output_video_name)}")
# =============================================================
# Entry Point
# =============================================================
if __name__ == "__main__":
main()
Key Changes Made:
-
Removed Multiprocessing Imports and Usage:
- Removed:
from concurrent.futures import ProcessPoolExecutor, as_completed and import multiprocessing.
- Removed: All code related to
ProcessPoolExecutor and multiprocessing.
-
Simplified process_single_frame Function:
- Now accepts
frame and render_model directly without packaging them into tuples.
- This function is called sequentially for each frame.
-
Sequential Frame Processing:
- Replaced the
ProcessPoolExecutor block with a simple for loop that processes each frame one by one.
- Utilizes
tqdm for progress visualization.
-
Injected renderModel into process_single_frame:
- Since we’re processing frames sequentially, we can pass
renderModel directly, avoiding the need to reload the model in each subprocess.
-
Error Handling:
- Maintained robust error handling to ensure that any issues during frame processing don't crash the entire script without proper logging.
Benefits of Sequential Processing:
- Simpler Debugging: Easier to identify and fix issues since everything runs in a single process.
- Resource Management: Avoids complexities related to sharing resources across multiple processes.
- Reduced Overhead: Eliminates the overhead associated with creating and managing multiple processes, which can be beneficial for smaller tasks or when multiprocessing introduces more problems than it solves.
Potential Next Steps:
-
Investigate the NoneType Error:
- While removing multiprocessing may eliminate the immediate error, it's essential to understand why
RenderModel.interface(frame) is returning None.
- Add additional logging inside the
RenderModel to trace why None is being returned.
- Ensure that
RenderModel is correctly loaded and that each frame being passed is valid.
-
Optimize Frame Processing:
- If sequential processing is too slow, consider optimizing the
RenderModel or the frame processing logic.
- Profiling the code can help identify bottlenecks.
-
Validate Input Frames:
- Ensure that
mouth_frame contains valid frames.
- Add checks to verify the integrity and format of each frame before processing.
-
Resource Cleanup:
- Ensure all resources (like video captures and writers) are properly released, even in cases of unexpected errors.
Example Debugging Steps for the NoneType Error
To specifically address the 'NoneType' object has no attribute 'get' error, consider the following:
-
Check RenderModel.interface(frame) Output:
- Add logging to inspect the output of the
interface method.
def process_single_frame(frame, render_model):
"""
Process a single video frame using the RenderModel.
"""
try:
processed_frame = render_model.interface(frame)
if processed_frame is None:
logging.warning("RenderModel returned None for a frame.")
processed_frame = np.ones_like(frame) * 255 # White frame as placeholder
return processed_frame
except Exception as e:
logging.error(f"Error processing frame: {e}")
return np.ones_like(frame) * 255 # White frame as placeholder
-
Ensure RenderModel is Properly Initialized:
- Verify that the model is loaded correctly and that all necessary resources are available.
-
Validate Input Frames:
- Ensure that each frame being passed to the
RenderModel is valid and not corrupted.
for idx, frame in enumerate(tqdm.tqdm(mouth_frame, desc="Processing Frames")):
if frame is None:
logging.error(f"Frame {idx} is None. Skipping processing.")
continue
processed_frame = process_single_frame(frame, renderModel)
videoWriter.write(processed_frame)
-
Review RenderModel Implementation:
- If you have access to the
RenderModel code, ensure that the interface method handles all expected inputs and edge cases gracefully.
By following these steps and utilizing the revised script without multithreading, you should be able to mitigate the immediate issue and further debug any underlying problems with frame processing.
If you have any additional questions or need further assistance, feel free to ask!