from openai import OpenAI
# Khởi tạo client
client = OpenAI(
api_key="<LLMOXY_API_KEY>", # Điền token của bạn
base_url="https://llmoxy.com/v1" # Điểm truy cập API
)
# Gửi yêu cầu
response = client.chat.completions.create(
model="gpt-5.4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
stream=False
)
print(response.choices[0].message.content)
import cv2
import base64
import requests
import os
import math
class VideoAnalyzer:
def __init__(self, video_path):
self.video_path = video_path
if not os.path.exists(video_path):
raise FileNotFoundError(f"❌ Không tìm thấy tệp video: {video_path}")
def get_metadata(self):
"""1. Lấy các thông số kỹ thuật cơ bản của video"""
cap = cv2.VideoCapture(self.video_path)
if not cap.isOpened():
return None
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
duration = frame_count / fps if fps > 0 else 0
cap.release()
return {
"width": width,
"height": height,
"fps": round(fps, 2),
"frame_count": frame_count,
"duration_sec": round(duration, 2),
"file_size_mb": round(os.path.getsize(self.video_path) / (1024 * 1024), 2)
}
def extract_keyframes(self, max_frames=5, target_width=512):
"""2. Trích xuất khung hình chính để AI phân tích"""
print("📸 Đang trích xuất khung hình chính...")
cap = cv2.VideoCapture(self.video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames == 0:
return []
interval = max(1, total_frames // max_frames)
base64_frames = []
for i in range(0, total_frames, interval):
if len(base64_frames) >= max_frames:
break
cap.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame = cap.read()
if ret:
h, w, _ = frame.shape
aspect_ratio = h / w
new_height = int(target_width * aspect_ratio)
resized_frame = cv2.resize(frame, (target_width, new_height))
_, buffer = cv2.imencode('.jpg', resized_frame)
base64_str = base64.b64encode(buffer).decode('utf-8')
base64_frames.append(base64_str)
cap.release()
print(f"✅ Đã trích xuất thành công {len(base64_frames)} khung hình")
return base64_frames
def analyze_content_with_ai(self, api_key, base64_frames):
"""3. Gọi mô hình thị giác lớn để phân tích nội dung video"""
print("🧠 Đang yêu cầu AI phân tích nội dung video...")
url = "https://llmoxy.com/v1/chat/completions"
content_payload = [
{"type": "text", "text": "Đây là vài khung hình được trích từ cùng một video theo thứ tự thời gian. Hãy mô tả chi tiết điều gì đang xảy ra trong video này, bao gồm bối cảnh, hành động của nhân vật, không khí và sự kiện chính."}
]
for b64 in base64_frames:
content_payload.append({
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{b64}",
"detail": "low"
}
})
payload = {
"model": "gpt-5.4",
"messages": [{"role": "user", "content": content_payload}],
"max_tokens": 1000,
"stream": True
}
try:
response = requests.post(url, headers={"Authorization": f"Bearer {api_key}"}, json=payload, stream=True)
print("
📝 Báo cáo phân tích video:
" + "="*30)
full_analysis = ""
for line in response.iter_lines():
if line:
decoded = line.decode('utf-8')
if decoded.startswith('data: ') and decoded != 'data: [DONE]':
try:
chunk = decoded[6:]
import json
delta = json.loads(chunk)['choices'][0]['delta'].get('content', '')
print(delta, end='', flush=True)
full_analysis += delta
except:
pass
print("
" + "="*30)
return full_analysis
except Exception as e:
print(f"❌ Phân tích thất bại: {e}")
return None
# Ví dụ sử dụng
if __name__ == "__main__":
video_file = r"đường dẫn tới tệp video của bạn.mp4" # Thay bằng đường dẫn tới tệp video của bạn
my_api_key = "<LLMOXY_API_KEY>" # Thay bằng API Key của bạn
if not os.path.exists(video_file):
print(f"⚠️ Không tìm thấy {video_file}, vui lòng chuẩn bị một tệp video trước.")
else:
analyzer = VideoAnalyzer(video_file)
meta = analyzer.get_metadata()
print(f"
📊 Metadata video: {meta}")
frames = analyzer.extract_keyframes(max_frames=5)
if frames:
analyzer.analyze_content_with_ai(my_api_key, frames)
import requests, json, base64
API_URL = "https://llmoxy.com/v1/chat/completions"
API_KEY = "Bearer <LLMOXY_API_KEY>" # Thay bằng API Key của bạn
def analyze_image(img_path):
"""Phân tích ảnh"""
with open(img_path, "rb") as f:
img_base64 = base64.b64encode(f.read()).decode()
payload = {
"model": "gpt-5.4", # Tên mô hình
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Hãy mô tả bức ảnh này"},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img_base64}"}
}
]
}],
"stream": True
}
headers = {
"Content-Type": "application/json",
"Authorization": API_KEY
}
response = requests.post(API_URL, json=payload, headers=headers, stream=True)
for line in response.iter_lines():
if line:
line = line.decode('utf-8').replace('data: ', '')
if line.strip() == '[DONE]': break
try:
data = json.loads(line)
if content := data['choices'][0]['delta'].get('content'):
print(content, end="", flush=True)
except:
continue
print()
# Ví dụ sử dụng
analyze_image(r"đường dẫn tới ảnh của bạn.jpg") # Thay bằng đường dẫn ảnh thực tế
import requests
import time
import json
import os
def generate_video_stream_with_retry(prompt, api_key, max_retries=3):
"""Hàm lấy chỉ thị tạo video dạng streaming với cơ chế thử lại"""
base_url = "https://llmoxy.com/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": "veo_3_1",
"messages": [
{
"role": "user",
"content": f"Hãy giúp tôi tạo một video, mô tả là: {prompt}. Hãy cho tôi biết các bước tạo video hoặc trực tiếp cung cấp liên kết video."
}
],
"max_tokens": 5000,
"temperature": 0.7,
"stream": True
}
for attempt in range(max_retries):
print(f"
🔄 Lần thử {attempt + 1}/{max_retries}...")
full_content = ""
try:
response = requests.post(base_url, headers=headers, json=payload, timeout=120, stream=True)
if response.status_code != 200:
print(f"❌ Yêu cầu thất bại, mã trạng thái: {response.status_code}")
if 500 <= response.status_code < 600:
print("⏳ Lỗi phía máy chủ, sẽ đợi rồi thử lại...")
time.sleep(5)
continue
else:
return None
print("✅ Kết nối thành công, bắt đầu nhận luồng dữ liệu...
")
print("-" * 30)
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith('data: '):
data_str = decoded_line[6:]
if data_str.strip() == '[DONE]':
print("
" + "-" * 30)
print("
✅ Truyền luồng kết thúc")
break
try:
data_json = json.loads(data_str)
delta = data_json['choices'][0]['delta'].get('content', '')
if delta:
print(delta, end='', flush=True)
full_content += delta
except json.JSONDecodeError:
continue
if full_content:
with open("ai_response.txt", "w", encoding="utf-8") as f:
f.write(full_content)
print(f"📝 Câu trả lời đầy đủ đã được lưu vào ai_response.txt")
return full_content
else:
print("⚠️ Không nhận được nội dung nào")
return None
except requests.exceptions.Timeout:
print("⏰ Kết nối quá thời gian")
time.sleep(5)
continue
except Exception as e:
print(f"❌ Lỗi không xác định: {e}")
return None
print(f"😞 Sau {max_retries} lần thử vẫn thất bại")
return None
# Ví dụ sử dụng
if __name__ == "__main__":
my_api_key = "<LLMOXY_API_KEY>" # Thay bằng API Key của bạn
result = generate_video_stream_with_retry(
prompt="một chú chó lướt sóng trên biển",
api_key=my_api_key,
max_retries=5
)
if result:
print("
🎬 Hoàn thành nhiệm vụ")
else:
print("
❌ Nhiệm vụ thất bại")
import requests
import json
import os
import re
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, Any, List
from urllib.parse import urlparse
class ImageGenerator:
def __init__(self):
self.api_key = "<LLMOXY_API_KEY>" # Thay bằng API key của bạn
self.api_url = "https://llmoxy.com/v1/chat/completions"
self.model = "nano-banana"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
def generate_image(self, prompt: str, save_dir: str = "./generated_images") -> Dict[str, Any]:
"""Tạo ảnh và trả về liên kết ảnh"""
Path(save_dir).mkdir(parents=True, exist_ok=True)
payload = {
"model": self.model,
"messages": [{"role": "user", "content": f"Generate an image based on this prompt: {prompt}"}],
"max_tokens": 1000
}
print(f"Đang tạo ảnh...")
print(f"Prompt: {prompt}")
try:
response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=600)
if response.status_code == 200:
return self._process_response(response, prompt, save_dir)
else:
print(f"Yêu cầu API thất bại: {response.status_code}")
return {"success": False, "error": f"HTTP {response.status_code}", "image_links": []}
except requests.exceptions.RequestException as e:
print(f"Yêu cầu ngoại lệ: {e}")
return {"success": False, "error": str(e), "image_links": []}
def _process_response(self, response, prompt, save_dir):
result = {"success": False, "image_links": [], "content": "", "error": None}
try:
response_data = response.json()
if "choices" in response_data and response_data["choices"]:
content = response_data["choices"][0]["message"]["content"]
result["content"] = content
print(f"Nội dung phản hồi API: {content}")
# Trích xuất liên kết ảnh
url_patterns = [
r'https?://[^\s]+?\.(?:jpg|jpeg|png|gif|bmp|webp)',
r'https?://[^\s]+?/image/[^\s]+',
]
found_links = []
for pattern in url_patterns:
matches = re.findall(pattern, content, re.IGNORECASE)
found_links.extend(matches)
if found_links:
result["success"] = True
result["image_links"] = found_links
print(f"Tìm thấy liên kết ảnh: {found_links}")
else:
result["success"] = True
result["note"] = "API trả về mô tả văn bản, không tìm thấy liên kết ảnh"
except Exception as e:
result["error"] = f"Xử lý phản hồi thất bại: {e}"
return result
def main():
print("🎨 Script tạo ảnh")
print("-" * 50)
generator = ImageGenerator()
prompt = "một chú chó con đáng yêu đang chơi trong vườn" # Sửa nội dung prompt tại đây
result = generator.generate_image(prompt=prompt, save_dir="./test_images")
print("
" + "=" * 50)
if result.get("success", False):
print("✅ Yêu cầu thành công!")
if result.get("image_links"):
print(f"
📷 Tìm thấy {len(result['image_links'])} liên kết ảnh:")
for i, link in enumerate(result["image_links"], 1):
print(f" {i}. {link}")
else:
print(f"❌ Tạo thất bại: {result.get('error', 'Lỗi không xác định')}")
if __name__ == "__main__":
main()
Nhận diện ảnh Nếu cần gửi ảnh, hãy sử dụng mô hình gpt-5.4 và tham khảo định dạng OpenAI Vision tiêu chuẩn.
