TDN-M commited on
Commit
0ffce02
·
verified ·
1 Parent(s): 21aef47

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -0
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from groq import Groq
4
+ from huggingface_hub import InferenceClient
5
+ from moviepy.editor import VideoFileClip
6
+ import numpy as np
7
+ from io import BytesIO
8
+
9
+ # Lưu khóa API
10
+ if 'GROQ_API_KEY' not in os.environ:
11
+ os.environ['GROQ_API_KEY'] = input('Nhập khóa API Groq của bạn: ')
12
+ if 'HF_TOKEN' not in os.environ:
13
+ os.environ['HF_TOKEN'] = input('Nhập Hugging Face API Token của bạn: ')
14
+
15
+ MAX_VIDEO_SIZE_MB = 35
16
+
17
+ # Hàm gọi Groq API
18
+ def call_groq_api(prompt, model_name="llama3-70b-8192", max_tokens=500):
19
+ client = Groq(api_key=os.environ.get('GROQ_API_KEY'))
20
+ response = client.chat.completions.create(
21
+ model=model_name,
22
+ messages=prompt,
23
+ max_tokens=max_tokens
24
+ )
25
+ return response.choices[0].message.content
26
+
27
+ # Hàm trích xuất audio từ video
28
+ def extract_audio_from_video(video_path):
29
+ try:
30
+ video = VideoFileClip(video_path)
31
+ audio_path = "temp_audio.mp3"
32
+ video.audio.write_audiofile(audio_path)
33
+ video.close()
34
+ return audio_path
35
+ except Exception as e:
36
+ raise Exception(f"Lỗi khi trích xuất audio: {str(e)}")
37
+
38
+ # Hàm trích xuất thumbnails từ video
39
+ def extract_thumbnails(video_path, num_frames=6):
40
+ try:
41
+ video = VideoFileClip(video_path)
42
+ duration = video.duration
43
+ step = duration / num_frames
44
+ thumbnails = []
45
+ for i in range(num_frames):
46
+ frame_time = i * step
47
+ frame = video.get_frame(frame_time)
48
+ thumbnails.append(frame)
49
+ video.close()
50
+ return thumbnails
51
+ except Exception as e:
52
+ raise Exception(f"Lỗi khi trích xuất thumbnails: {str(e)}")
53
+
54
+ # Hàm gọi Hugging Face Inference API để chuyển audio thành văn bản
55
+ def transcribe_audio(audio_path):
56
+ try:
57
+ client = InferenceClient(api_key=os.environ.get('HF_TOKEN'))
58
+ with open(audio_path, "rb") as audio_file:
59
+ transcription = client.automatic_speech_recognition(
60
+ audio_file,
61
+ model="openai/whisper-tiny"
62
+ )
63
+ return transcription['text']
64
+ except Exception as e:
65
+ raise Exception(f"Lỗi khi chuyển audio thành văn bản: {str(e)}")
66
+
67
+ # Hàm tạo prompt cho Groq
68
+ def create_prompt(social_media_type, transcription_text):
69
+ system_msg = (
70
+ "Bạn là chuyên gia trong việc tạo nội dung mạng xã hội và tạo bài đăng hiệu quả dựa trên nội dung người dùng. "
71
+ "Tuân thủ quy tắc và ràng buộc của nền tảng mạng xã hội."
72
+ )
73
+ user_msg = f"Nền tảng: {social_media_type}\nNội dung văn bản: {transcription_text}"
74
+ return [
75
+ {"role": "system", "content": system_msg},
76
+ {"role": "user", "content": user_msg}
77
+ ]
78
+
79
+ # Hàm xử lý chính
80
+ def process_and_generate_post(video_file, social_media_type, progress=gr.Progress()):
81
+ progress(0, desc="Đang khởi tạo...")
82
+
83
+ if not video_file:
84
+ return "Vui lòng tải lên tệp video.", None, None, None
85
+
86
+ try:
87
+ # Kiểm tra kích thước tệp video
88
+ video_size = os.path.getsize(video_file) / (1024 * 1024) # Chuyển sang MB
89
+ if video_size > MAX_VIDEO_SIZE_MB:
90
+ return f"Tệp video lớn hơn {MAX_VIDEO_SIZE_MB} MB. Vui lòng tải lên tệp nhỏ hơn.", None, None, None
91
+
92
+ progress(0.2, desc="Đang trích xuất audio...")
93
+ audio_path = extract_audio_from_video(video_file)
94
+
95
+ progress(0.4, desc="Đang trích xuất thumbnails...")
96
+ thumbnails = extract_thumbnails(video_file)
97
+
98
+ progress(0.6, desc="Đang chuyển audio thành văn bản...")
99
+ transcription_text = transcribe_audio(audio_path)
100
+
101
+ progress(0.8, desc="Đang tạo bài đăng mạng xã hội...")
102
+ prompt = create_prompt(social_media_type, transcription_text)
103
+ social_media_post = call_groq_api(prompt)
104
+
105
+ # Xóa tệp audio tạm
106
+ if os.path.exists(audio_path):
107
+ os.remove(audio_path)
108
+
109
+ return social_media_post, thumbnails, transcription_text, audio_path
110
+
111
+ except Exception as e:
112
+ return f"Đã xảy ra lỗi: {str(e)}", None, None, None
113
+
114
+ # Giao diện Gradio
115
+ def gradio_interface():
116
+ with gr.Blocks(theme=gr.themes.Base()) as demo:
117
+ gr.Markdown(
118
+ """
119
+ 📹 Công cụ Tạo Bài Đăng Mạng Xã Hội từ Video
120
+ Biến video của bạn thành nội dung mạng xã hội hấp dẫn bằng AI
121
+ """
122
+ )
123
+
124
+ with gr.Row():
125
+ # Cột bên trái - Điều khiển đầu vào
126
+ with gr.Column():
127
+ video_input = gr.File(
128
+ label="Tải lên Video",
129
+ file_types=[".mp4", ".avi", ".mov"],
130
+ height='400px'
131
+ )
132
+
133
+ with gr.Group():
134
+ gr.Markdown("### 🎯 Nền tảng Mục tiêu")
135
+ social_media_type = gr.Radio(
136
+ choices=[
137
+ "X (Twitter)",
138
+ "Facebook",
139
+ "LinkedIn",
140
+ "Instagram"
141
+ ],
142
+ value="X (Twitter)",
143
+ label="Chọn nơi bạn muốn chia sẻ:",
144
+ interactive=True
145
+ )
146
+
147
+ generate_btn = gr.Button(
148
+ "🚀 Tạo Bài Đăng",
149
+ scale=1,
150
+ size="lg",
151
+ variant="primary"
152
+ )
153
+
154
+ # Cột bên phải - Hiển thị kết quả
155
+ with gr.Column():
156
+ output = gr.Textbox(
157
+ label="✨ Bài Đăng Đã Tạo",
158
+ show_copy_button=True,
159
+ lines=4
160
+ )
161
+
162
+ gr.Markdown("### 🖼️ Hình thu nhỏ")
163
+ thumbnail = gr.Gallery(
164
+ label="Chọn hình thu nhỏ ưa thích",
165
+ show_download_button=True,
166
+ show_fullscreen_button=True,
167
+ height='200px',
168
+ object_fit="contain"
169
+ )
170
+
171
+ gr.Markdown("### 📝 Văn bản Đã Trích xuất")
172
+ df_output = gr.Textbox(
173
+ label="Văn bản Đã Trích xuất",
174
+ show_copy_button=True,
175
+ lines=8
176
+ )
177
+
178
+ gr.Markdown("### 🎵 Âm thanh Đã Trích xuất")
179
+ audio = gr.Audio(
180
+ label="Âm thanh",
181
+ show_download_button=True,
182
+ type="filepath"
183
+ )
184
+
185
+ # Kết nối nút nhấn với hàm xử lý
186
+ generate_btn.click(
187
+ fn=process_and_generate_post,
188
+ inputs=[video_input, social_media_type],
189
+ outputs=[output, thumbnail, df_output, audio],
190
+ show_progress="full",
191
+ trigger_mode='once'
192
+ )
193
+
194
+ return demo
195
+
196
+ # Khởi chạy giao diện Gradio
197
+ if __name__ == "__main__":
198
+ demo = gradio_interface()
199
+ demo.launch(
200
+ server_name="0.0.0.0",
201
+ server_port=7860,
202
+ share=False,
203
+ show_api=False,
204
+ show_error=False,
205
+ ssl_verify=True,
206
+ quiet=True
207
+ )