Evet, verdiğiniz ses transkript fonksiyonunu mevcut kodunuzla entegre edebiliriz. Spesifik olarak, bir videonun ses dosyasını çıkararak tanıyabilir ve dokümanlardan elde edilen başlıklarla eşleştirerek doğru başlığı seçebiliriz. Burada match_audio_with_headlines fonksiyonunu sisteme entegre edeceğiz ve dokümandan alınan başlıklardır (headline dictionary).
Aşağıda, tüm sistemi nasıl entegre edeceğinizi gösteren bir düzenleme yapılmıştır.
Kodun Güncellenmiş Hali
import os
import io
import shutil
from google.colab import drive, auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from PIL import Image, ImageDraw, ImageFont
import moviepy.editor as mp
import speech_recognition as sr # Yeni kütüphane
from google.auth import default
# Google Drive bağlantısı kurma
drive.mount('/content/drive')
# Google API kimlik doğrulama
auth.authenticate_user()
creds, _ = default()
drive_service = build('drive', 'v3', credentials=creds)
docs_service = build('docs', 'v1', credentials=creds)
# Dosya indirme fonksiyonu
def download_file(service, file_id, file_name):
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while not done:
status, done = downloader.next_chunk()
fh.seek(0)
with open(file_name, "wb") as f:
f.write(fh.read())
# Google Doküman başlıklarını alma fonksiyonu
def get_document_title(document_id, retries=3):
attempt = 0
while attempt < retries:
try:
document = docs_service.documents().get(documentId=document_id).execute()
content = document.get('body').get('content', [])
for element in content:
if 'paragraph' in element:
for textRun in element['paragraph']['elements']:
if 'textRun' in textRun and 'content' in textRun['textRun']:
text = textRun['textRun']['content'].strip()
if text.startswith("Video Title:"):
return text.replace("Video Title:", "").strip().split('.')[0]
return "Başlık bulunamadı"
except HttpError as e:
print(f"Error retrieving document {document_id}: {e}")
attempt += 1
time.sleep(2 ** attempt) # Exponential backoff
return ""
# Metni iki satıra bölme ve ekleme fonksiyonu
def add_text_to_png(image_path, text, x_offset=30, max_words_per_line=5):
img = Image.open(image_path)
draw = ImageDraw.Draw(img)
font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font = ImageFont.truetype(font_path, 8)
words = text.split()
lines = [' '.join(words[i:i + max_words_per_line]) for i in range(0, len(words), max_words_per_line)]
line_heights = []
line_widths = []
for line in lines:
bbox = draw.textbbox((0, 0), line, font=font)
line_width = bbox[2] - bbox[0]
line_height = bbox[3] - bbox[1]
line_widths.append(line_width)
line_heights.append(line_height)
total_text_height = sum(line_heights) + (len(lines) - 1) * 5
vertical_center = (img.height - total_text_height) // 2 + 255
current_y = vertical_center
for i, line in enumerate(lines):
line_position = ((img.width - line_widths[i]) // 2 + x_offset, current_y)
draw.text(line_position, line, font=font, fill="white")
current_y += line_heights[i] + 5
img.save(image_path)
print(f"Added text to {image_path}")
# Video üzerine PNG dosyasını ekleme ve metin ekleme fonksiyonu
def overlay_image_on_video(video_path, overlay_image_path, output_path):
video = mp.VideoFileClip(video_path)
overlay = mp.ImageClip(overlay_image_path).set_duration(video.duration).set_position(("center", "bottom"))
final_video = mp.CompositeVideoClip([video, overlay])
final_video.write_videofile(output_path, codec='libx264', threads=4, audio_codec='aac')
print(f"Overlay added to {video_path}, output saved to {output_path}")
# Başlıklar ile ses eşleştirici fonksiyon
def match_audio_with_headlines(video_path, headlines):
try:
recognizer = sr.Recognizer()
audio_path = "/content/temp_audio.wav"
# Videodan sesi ayır ve ses dosyasını oluştur
video = mp.VideoFileClip(video_path)
video.audio.write_audiofile(audio_path)
print(f"Ses dosyası {audio_path} olarak oluşturuldu.")
# Ses dosyasını analiz et
with sr.AudioFile(audio_path) as source:
print("Sesin transkripsiyonu başlatılıyor...")
audio_data = recognizer.record(source)
transcript = recognizer.recognize_google(audio_data, language="tr-TR")
print("Transkript:", transcript)
# Başlıklar ile transkripti eşleştir
matched_segments = []
for key, headline in headlines.items():
if all(word in transcript for word in headline.split()[:5]):
print(f"Eşleşme bulundu: {key} -> {headline}")
matched_segments.append((key, headline))
if not matched_segments:
print("Eşleşen segment bulunamadı. Başlıklar ve transkript uyuşmuyor olabilir.")
return matched_segments
except Exception as e:
print(f"Ses analizi hatası: {str(e)}")
return []
# Google Drive'a sonuçları kaydetme fonksiyonu
def upload_to_drive(file_path, folder_id):
file_metadata = {
'name': os.path.basename(file_path),
'parents': [folder_id]
}
media = MediaFileUpload(file_path, mimetype='video/mp4')
drive_service.files().create(body=file_metadata, media_body=media).execute()
print(f"Uploaded {file_path} to Drive folder {folder_id}")
# Klasörü işle ve dosyaları listele
folder_id = "1nSmoj_SgPH6I_7AKZMYU59JZayBtGRSq"
results = drive_service.files().list(q=f"'{folder_id}' in parents",
fields="files(id, name, mimeType)").execute()
files = results.get('files', [])
print("Listed files:", files)
# lower.png dosyasını indir ve işle
lower_image_path = "lower.png"
download_file(drive_service, "1BFn29V7wIvv1LhQc0lEFMvdEboQLR3sA", lower_image_path)
print("Downloaded lower.png")
# Doküman ve video başlıklarını işleme
headlines = {}
for file in files:
if file['mimeType'] == 'application/vnd.google-apps.document':
document_id = file['id']
document_name = file['name']
video_title = get_document_title(document_id)
if not video_title:
print(f"Skipping document {document_name} because it has no title.")
continue
headlines[file['id']] = video_title
# Videoları işle
for video_file in files:
if video_file['mimeType'].startswith('video/'):
video_id = video_file['id']
video_name = video_file['name']
# Videoyu indir
video_path = f"{video_name}"
download_file(drive_service, video_id, video_path)
print(f"Downloaded video: {video_name}")
# Sesi analiz et ve başlığı bul
matched_segments = match_audio_with_headlines(video_path, headlines)
if not matched_segments:
print(f"Başlık bulunamadı, videoyu atlıyor: {video_name}")
continue
# İlk eşleşen başlık alınır
_, appropriate_title = matched_segments[0]
# Lower third'e metni ekle
lower_image_copy = f"lower_{video_name}.png"
shutil.copy(lower_image_path, lower_image_copy)
add_text_to_png(lower_image_copy, appropriate_title)
# Overlay görüntüsünü videoya ekle
output_video_path = f"output_{video_name}"
overlay_image_on_video(video_path, lower_image_copy, output_video_path)
# İşlenmiş videoyu tekrar Drive'a yükleyin
upload_to_drive(output_video_path, folder_id)
print(f"Processed and uploaded video: {video_name}")
Açıklama
-
Başlık ve Ses Eşleştirme:
match_audio_with_headlines fonksiyonu, tanımlanan videoda geçen ilgili başlığı (headlines) ses dökümü ile eşleştiriyor.
-
Eşleşme Kontrolü:
- Her video için
transcript ile headlines’i karşılaştırıp doğru başlığı buluyoruz.
-
Lower Third ve Overlay:
- Başlık eşleşmesi yapıldıktan sonra video üzerine lower third ekleniyor.
-
Yükleme:
- Yeni işlenen video önce yerel olarak kaydedilir ve ardından Google Drive'a yüklenir.
Tamamlanan kodunuz, hem bir başlık hem de ses transkripti olan videolarda çalışacaktır.