Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from sercetexam9/Nguyen_AI: direct link, hf CLI and curl.
- Browser
- Download file 5.81 kB
-
https://huggingface.co/spaces/sercetexam9/Nguyen_AI/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/sercetexam9/Nguyen_AI/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/sercetexam9/Nguyen_AI/resolve/main/src/streamlit_app.py
5.81 kB
| import streamlit as st | |
| import os | |
| import requests | |
| import tempfile | |
| import json | |
| from openai import OpenAI | |
| import replicate | |
| from moviepy.editor import VideoFileClip, concatenate_videoclips | |
| # --- 1. CẤU HÌNH HỆ THỐNG & API --- | |
| # Lấy API Key từ Secrets của Hugging Face | |
| OPENAI_API_KEY = "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" | |
| REPLICATE_API_TOKEN = "r8_Yrgp81AWoQFI5tNSu7DA92skWSiqyXR2SlpMn" | |
| # Khởi tạo OpenAI Client | |
| client = OpenAI(api_key=OPENAI_API_KEY) | |
| # --- 2. GIAO DIỆN NGƯỜI DÙNG (UI) --- | |
| st.set_page_config(page_title="AI Video Generator 1 Phút", page_icon="🎬", layout="centered") | |
| # Bảo mật bằng mật khẩu đơn giản | |
| PASSWORD = "123" # Bạn có thể thay đổi mật khẩu này | |
| st.sidebar.title("🔐 Xác thực") | |
| user_pass = st.sidebar.text_input("Nhập mật khẩu để bắt đầu:", type="password") | |
| if user_pass != PASSWORD: | |
| st.info("Vui lòng nhập mật khẩu ở thanh bên trái để sử dụng ứng dụng.") | |
| st.stop() | |
| st.title("🎬 AI Video Generator (1 Phút)") | |
| st.markdown(""" | |
| Hệ thống này sẽ giúp bạn tạo một video AI chất lượng dài **60 giây** bằng cách: | |
| 1. Dùng **GPT-4o-mini** để chia kịch bản thành 10 cảnh. | |
| 2. Dùng **HunyuanVideo (via Replicate)** để tạo 10 đoạn clip 6 giây. | |
| 3. Tự động nối lại thành video hoàn chỉnh. | |
| """) | |
| user_prompt = st.text_area("Nhập ý tưởng video của bạn (Ví dụ: Một chuyến du hành xuyên thời gian từ thời tiền sử đến tương lai):", height=150) | |
| # --- 3. HÀM XỬ LÝ CHÍNH --- | |
| def generate_1min_video(main_prompt): | |
| try: | |
| # BƯỚC 1: CHIA KỊCH BẢN | |
| st.info("🤖 Bước 1: Đang dùng AI phác thảo 10 phân cảnh...") | |
| system_msg = ( | |
| "Bạn là một đạo diễn điện ảnh. Hãy chia ý tưởng của người dùng thành đúng 10 cảnh phim. " | |
| "Mỗi cảnh mô tả hình ảnh cực kỳ chi tiết (không có lời thoại). " | |
| "Trả về kết quả dưới dạng một mảng JSON thuần túy gồm 10 chuỗi văn bản (strings). " | |
| "Ví dụ: [\"cảnh 1...\", \"cảnh 2...\", ...]" | |
| ) | |
| response = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[ | |
| {"role": "system", "content": system_msg}, | |
| {"role": "user", "content": main_prompt} | |
| ], | |
| response_format={ "type": "json_object" } # Ép kết quả về JSON | |
| ) | |
| # Parse kết quả JSON | |
| raw_json = json.loads(response.choices[0].message.content) | |
| # Lấy list scenes (tùy theo cách GPT trả về key, ta lấy value đầu tiên nếu là dict) | |
| scenes = list(raw_json.values())[0] if isinstance(raw_json, dict) else raw_json | |
| if len(scenes) < 10: | |
| st.error("Lỗi: AI không tạo đủ 10 cảnh. Vui lòng thử lại.") | |
| return None | |
| # BƯỚC 2: TẠO VIDEO CHO TỪNG CẢNH | |
| video_paths = [] | |
| progress_bar = st.progress(0) | |
| for i, scene_desc in enumerate(scenes[:10]): | |
| st.write(f"🎥 Đang tạo cảnh {i+1}/10: {scene_desc[:70]}...") | |
| # Gọi API Replicate (Model HunyuanVideo - Tiết kiệm nhất) | |
| # Model ID: lucataco/hunyuan-video | |
| output = replicate.run( | |
| "wan-video/wan-2.2-t2v-fast", | |
| input={ | |
| "prompt": scene_desc, | |
| "video_size": "854x480", # Độ phân giải 480p để tiết kiệm chi phí | |
| "duration": 6, # Mỗi cảnh 6 giây | |
| "infer_steps": 30 | |
| } | |
| ) | |
| # Tải video từ URL trả về và lưu vào file tạm | |
| video_url = output | |
| res = requests.get(video_url) | |
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") | |
| temp_file.write(res.content) | |
| video_paths.append(temp_file.name) | |
| # Cập nhật thanh tiến trình | |
| progress_bar.progress((i + 1) / 10) | |
| # BƯỚC 3: NỐI VIDEO | |
| st.info("🎞️ Bước 2: Đang nối các đoạn clip thành video 1 phút hoàn chỉnh...") | |
| clips = [VideoFileClip(p) for p in video_paths] | |
| final_video = concatenate_videoclips(clips, method="compose") | |
| output_filename = "ai_final_video_1min.mp4" | |
| final_video.write_videofile(output_filename, codec="libx264", audio=False) | |
| # Đóng các clip để giải phóng bộ nhớ (Tránh treo server HF) | |
| for clip in clips: | |
| clip.close() | |
| return output_filename | |
| except Exception as e: | |
| st.error(f"❌ Đã xảy ra lỗi: {str(e)}") | |
| return None | |
| # --- 4. NÚT KÍCH HOẠT --- | |
| if st.button("🚀 BẮT ĐẦU GENERATE"): | |
| if not user_prompt: | |
| st.warning("Vui lòng nhập ý tưởng trước!") | |
| elif not OPENAI_API_KEY or not REPLICATE_API_TOKEN: | |
| st.error("Thiếu API Key trong phần Settings của Hugging Face!") | |
| else: | |
| result = generate_1min_video(user_prompt) | |
| if result: | |
| st.success("✅ Đã hoàn thành video 1 phút!") | |
| st.video(result) | |
| with open(result, "rb") as file: | |
| st.download_button( | |
| label="💾 Tải video về máy", | |
| data=file, | |
| file_name="video_ai_1phut.mp4", | |
| mime="video/mp4" | |
| ) | |