import gradio as gr import requests import os from ffmpy import FFmpeg def extract(url): # 마지막 슬래시(/)의 위치를 찾습니다. last_slash_index = url.rfind('/') # 마지막 슬래시 이전까지의 문자열을 추출합니다. return url[:last_slash_index] if last_slash_index != -1 else url # 동영상 파일 다운로드 함수, 다운로드한 파일의 수를 반환 def download_files_until_fail(base_url): i = 1 # 시작 번호 while True: url = f"{base_url}/{i}.ts" r = requests.get(url, stream=True) if r.status_code == 200: with open(f"video_parts/{i}.ts", 'wb') as f: for chunk in r.iter_content(1024): f.write(chunk) print(f"Downloaded {i}.ts") i += 1 else: print(f"Failed to download {i}.ts, stopping...") break return i - 1 # 마지막으로 성공적으로 다운로드한 파일 번호 반환 def download_files_until_fail_t(a): return int(512) # 파일 합치기 함수 def concatenate_files(num_files, output_folder, output_filename): output_path = os.path.join(output_folder, output_filename) # 폴더를 새로 생성 os.makedirs(output_folder, exist_ok=True) # 파일 생성 및 내용 작성 with open(output_path, 'wb') as outfile: for i in range(1, num_files + 1): filepath = f"video_parts/{i}.ts" if os.path.exists(filepath): with open(filepath, 'rb') as infile: outfile.write(infile.read()) print(f"Added {i}.ts to {output_path}") def refresh(drop): def get_folders_in_directory_except_specific_ones(directory_path, exclude_folders=('venv', '.idea', 'flagged', 'video_parts')): # directory_path 내의 항목들을 리스트로 가져옴 items = os.listdir(directory_path) # 해당 항목이 디렉토리인지 확인 후, 특정 폴더를 제외한 폴더 이름만 필터링 folders = [item for item in items if os.path.isdir(os.path.join(directory_path, item)) and item not in exclude_folders] # 폴더 이름들을 튜플로 변환하여 반환 return tuple(folders) # 현재 작업 디렉토리의 폴더 이름들을 튜플로 반환 (특정 폴더 제외) current_directory = os.getcwd() folders_tuple = get_folders_in_directory_except_specific_ones(current_directory) return gr.Dropdown(folders_tuple) def srch(name): return f'{name}/{name}.mp4', f'{name}/{name}.mp4' def save(name, link): if os.path.isdir(name) == True: return "이미 존재하는 이름입니다.", f'{name}/{name}.mp4' os.mkdir(name) f = open(f"{name}/{name}.txt", 'w') f.write(f'{link}') f.close() link = extract(link) num_files = download_files_until_fail(link) concatenate_files(num_files, name, f"{name}.ts") input_ts = f"{name}/{name}.ts" output_mp4 = f'{name}/{name}.mp4' ff = FFmpeg( inputs={input_ts: None}, outputs={output_mp4: '-c:v libx265 -crf 28'} # '-crf 28'은 출력 비디오의 품질을 설정합니다. 값이 낮을수록 품질이 좋고 파일 크기가 커집니다. ) ff.run() # ffmpeg를 사용하여 .ts 파일을 .mp4로 변환하는 명령을 구성합니다. #command = f'ffmpeg -i {input_ts} -c copy {output_mp4}' # subprocess.run을 사용하여 명령을 실행합니다. #subprocess.run(command, shell=True) return "saved", f'{name}/{name}.mp4' with gr.Blocks() as demo: with gr.Tab("Save"): name = gr.Textbox(label="저장할 이름") link = gr.Textbox(label="https://---/숫자.ts 그대로 입력") submit = gr.Button("제출") out = gr.Textbox() file = gr.File(interactive=False) submit.click(save, [name, link], [out, file]) with gr.Tab("Folder") as folder: drop = gr.Dropdown([]) file = gr.File(interactive=False) vid = gr.Video(interactive=False) drop.change(srch, [drop], [file, vid]) folder.select(refresh, [drop], [drop]) demo.launch(server_name="0.0.0.0")