import gradio as gr import pandas as pd import requests from bs4 import BeautifulSoup from docx import Document import os from openai import OpenAI import json from youtube_transcript_api import YouTubeTranscriptApi from moviepy.editor import VideoFileClip from pytube import YouTube import os from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload from googleapiclient.http import MediaIoBaseUpload import io from urllib.parse import urlparse, parse_qs # 假设您的环境变量或Secret的名称是GOOGLE_APPLICATION_CREDENTIALS_JSON # credentials_json_string = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON") # credentials_dict = json.loads(credentials_json_string) # SCOPES = ['https://www.googleapis.com/auth/drive'] # credentials = service_account.Credentials.from_service_account_info( # credentials_dict, scopes=SCOPES) # service = build('drive', 'v3', credentials=credentials) # # 列出 Google Drive 上的前10個文件 # results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute() # items = results.get('files', []) # if not items: # print('No files found.') # else: # print("=====Google Drive 上的前10個文件=====") # print('Files:') # for item in items: # print(u'{0} ({1})'.format(item['name'], item['id'])) OUTPUT_PATH = 'videos' OPEN_AI_KEY = os.getenv("OPEN_AI_KEY") client = OpenAI(api_key=OPEN_AI_KEY) # 初始化Google Drive服务 def init_drive_service(): credentials_json_string = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON") credentials_dict = json.loads(credentials_json_string) SCOPES = ['https://www.googleapis.com/auth/drive'] credentials = service_account.Credentials.from_service_account_info( credentials_dict, scopes=SCOPES) service = build('drive', 'v3', credentials=credentials) return service def create_folder_if_not_exists(service, folder_name, parent_id): print("检查是否存在特定名称的文件夹,如果不存在则创建") query = f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}' and '{parent_id}' in parents and trashed=false" response = service.files().list(q=query, spaces='drive', fields="files(id, name)").execute() folders = response.get('files', []) if not folders: # 文件夹不存在,创建新文件夹 file_metadata = { 'name': folder_name, 'mimeType': 'application/vnd.google-apps.folder', 'parents': [parent_id] } folder = service.files().create(body=file_metadata, fields='id').execute() return folder.get('id') else: # 文件夹已存在 return folders[0]['id'] # 检查Google Drive上是否存在文件 def check_file_exists(service, folder_name, file_name): query = f"name = '{file_name}' and '{folder_name}' in parents and trashed = false" response = service.files().list(q=query).execute() files = response.get('files', []) return len(files) > 0, files[0]['id'] if files else None def upload_to_drive(service, file_name, folder_id, content): print("上传文本内容到Google Drive指定的文件夹中") # 如果您的内容是字符串(文本),请使用io.StringIO # 对于二进制内容,请使用io.BytesIO file_metadata = {'name': file_name, 'parents': [folder_id]} # 这里我们假定content是文本,因此使用io.StringIO media = MediaFileUpload(io.StringIO(content), mimetype='text/plain') service.files().create(body=file_metadata, media_body=media, fields='id').execute() def upload_content_directly(service, file_name, folder_id, content): """ 直接将内容上传到Google Drive中的新文件。 """ file_metadata = {'name': file_name, 'parents': [folder_id]} # 使用io.StringIO为文本内容创建一个内存中的文件对象 fh = io.BytesIO(content.encode('utf-8')) media = MediaIoBaseUpload(fh, mimetype='text/plain', resumable=True) # 执行上传 service.files().create(body=file_metadata, media_body=media, fields='id').execute() def download_file_as_string(service, file_id): """ 从Google Drive下载文件并将其作为字符串返回。 """ request = service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() fh.seek(0) content = fh.read().decode('utf-8') return content def process_file(file): # 读取文件 if file.name.endswith('.csv'): df = pd.read_csv(file) text = df_to_text(df) elif file.name.endswith('.xlsx'): df = pd.read_excel(file) text = df_to_text(df) elif file.name.endswith('.docx'): text = docx_to_text(file) else: raise ValueError("Unsupported file type") df_string = df.to_string() # 宜蘭:移除@XX@符号 to | df_string = df_string.replace("@XX@", "|") # 根据上传的文件内容生成问题 questions = generate_questions(df_string) df_summarise = generate_df_summarise(df_string) # 返回按钮文本和 DataFrame 字符串 return questions[0] if len(questions) > 0 else "", \ questions[1] if len(questions) > 1 else "", \ questions[2] if len(questions) > 2 else "", \ df_summarise, \ df_string def df_to_text(df): # 将 DataFrame 转换为纯文本 return df.to_string() def docx_to_text(file): # 将 Word 文档转换为纯文本 doc = Document(file) return "\n".join([para.text for para in doc.paragraphs]) def format_seconds_to_time(seconds): """将秒数格式化为 时:分:秒 的形式""" hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) seconds = int(seconds % 60) return f"{hours:02}:{minutes:02}:{seconds:02}" def extract_youtube_id(url): parsed_url = urlparse(url) if "youtube.com" in parsed_url.netloc: # 对于标准链接,视频ID在查询参数'v'中 query_params = parse_qs(parsed_url.query) return query_params.get("v")[0] if "v" in query_params else None elif "youtu.be" in parsed_url.netloc: # 对于短链接,视频ID是路径的一部分 return parsed_url.path.lstrip('/') else: return None def process_youtube_link(link): # 使用 YouTube API 获取逐字稿 # 假设您已经获取了 YouTube 视频的逐字稿并存储在变量 `transcript` 中 video_id = extract_youtube_id(link) service = init_drive_service() parent_folder_id = '1GgI4YVs0KckwStVQkLa1NZ8IpaEMurkL' # youtube逐字稿圖檔的ID # 检查/创建视频ID命名的子文件夹 folder_id = create_folder_if_not_exists(service, video_id, parent_folder_id) file_name = f"{video_id}_transcript.txt" # 检查逐字稿是否存在 transcript = None exists, file_id = check_file_exists(service, folder_id, file_name) if not exists: # 获取逐字稿 transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['zh-TW']) transcript_text = json.dumps(transcript, ensure_ascii=False, indent=2) # 上传到Google Drive upload_content_directly(service, file_name, folder_id, transcript_text) print("逐字稿已上传到Google Drive") else: print("逐字稿已存在于Google Drive中") transcript_text = download_file_as_string(service, file_id) transcript = json.loads(transcript_text) # 基于逐字稿生成其他所需的输出 questions = generate_questions(transcript) df_summarise = generate_df_summarise(transcript) formatted_transcript = [] screenshot_paths = [] for entry in transcript: start_time = format_seconds_to_time(entry['start']) end_time = format_seconds_to_time(entry['start'] + entry['duration']) embed_url = get_embedded_youtube_link(video_id, entry['start']) # 截圖 screenshot_path = screenshot_youtube_video(video_id, entry['start']) line = { "start_time": start_time, "end_time": end_time, "text": entry['text'], "embed_url": embed_url, "screenshot_path": screenshot_path } formatted_transcript.append(line) screenshot_paths.append(screenshot_path) html_content = format_transcript_to_html(formatted_transcript) print("=====html_content=====") print(html_content) print("=====html_content=====") # 确保返回与 UI 组件预期匹配的输出 return questions[0] if len(questions) > 0 else "", \ questions[1] if len(questions) > 1 else "", \ questions[2] if len(questions) > 2 else "", \ df_summarise, \ html_content, \ screenshot_paths, def format_transcript_to_html(formatted_transcript): html_content = "" for entry in formatted_transcript: html_content += f"
{entry['text']}
" html_content += f"