from openai import OpenAI
# クライアントを初期化
client = OpenAI(
api_key="<LLMOXY_API_KEY>", # トークンを入力
base_url="https://llmoxy.com/v1" # API アクセスポイント
)
# リクエストを送信
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"❌ ビデオファイルが見つかりません: {video_path}")
def get_metadata(self):
"""1. ビデオの基本技術パラメータを取得"""
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. AI 分析用のキーフレームを抽出"""
print("📸 キーフレームを抽出中...")
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"✅ {len(base64_frames)} 個のキーフレームを正常に抽出")
return base64_frames
def analyze_content_with_ai(self, api_key, base64_frames):
"""3. ビジョン大モデルを呼び出してビデオ内容を解析"""
print("🧠 AI によるビデオ内容分析をリクエスト中...")
url = "https://llmoxy.com/v1/chat/completions"
content_payload = [
{"type": "text", "text": "これは同じビデオから時間順に抽出された数フレームです。このビデオで何が起こったか詳しく説明してください。シーン、人物の動作、雰囲気、主要なイベントを含めてください。"}
]
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("\n📝 ビデオ分析レポート:\n" + "="*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("\n" + "="*30)
return full_analysis
except Exception as e:
print(f"❌ 分析に失敗: {e}")
return None
# 使用例
if __name__ == "__main__":
video_file = r"あなたのビデオファイルパス.mp4" # あなたのビデオファイルパスに置き換え
my_api_key = "<LLMOXY_API_KEY>" # あなたの API Key に置き換え
if not os.path.exists(video_file):
print(f"⚠️ {video_file} が見つかりません。先にビデオファイルを準備してください。")
else:
analyzer = VideoAnalyzer(video_file)
meta = analyzer.get_metadata()
print(f"\n📊 ビデオメタデータ: {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>" # あなたの API Key に置き換え
def analyze_image(img_path):
"""画像を分析"""
with open(img_path, "rb") as f:
img_base64 = base64.b64encode(f.read()).decode()
payload = {
"model": "gpt-5.4", # モデル名
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "この画像を説明してください"},
{
"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()
# 使用例
analyze_image(r"あなたの画像パス.jpg") # 実際の画像パスに置き換え
import requests
import time
import json
import os
def generate_video_stream_with_retry(prompt, api_key, max_retries=3):
"""リトライメカニズム付きストリーミングビデオ生成指示取得関数"""
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"ビデオを生成してください。説明は:{prompt}。ビデオ生成の手順を教えるか、直接ビデオリンクを提供してください。"
}
],
"max_tokens": 5000,
"temperature": 0.7,
"stream": True
}
for attempt in range(max_retries):
print(f"\n🔄 試行 {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"❌ リクエスト失敗、ステータスコード: {response.status_code}")
if 500 <= response.status_code < 600:
print("⏳ サーバーエラー、再試行前に待機...")
time.sleep(5)
continue
else:
return None
print("✅ 接続成功、データストリームの受信を開始...\n")
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("\n" + "-" * 30)
print("\n✅ ストリーミング終了")
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"📝 完全なレスポンスを ai_response.txt に保存")
return full_content
else:
print("⚠️ コンテンツを受信しませんでした")
return None
except requests.exceptions.Timeout:
print("⏰ 接続タイムアウト")
time.sleep(5)
continue
except Exception as e:
print(f"❌ 不明なエラー: {e}")
return None
print(f"😞 {max_retries} 回の試行後も失敗")
return None
# 使用例
if __name__ == "__main__":
my_api_key = "<LLMOXY_API_KEY>" # あなたの API Key に置き換え
result = generate_video_stream_with_retry(
prompt="海でサーフィンする犬",
api_key=my_api_key,
max_retries=5
)
if result:
print("\n🎬 タスク完了")
else:
print("\n❌ タスク失敗")
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>" # あなたの API Key に置き換え
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]:
"""画像を生成して画像リンクを返す"""
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"画像を生成中...")
print(f"プロンプト: {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"API リクエスト失敗: {response.status_code}")
return {"success": False, "error": f"HTTP {response.status_code}", "image_links": []}
except requests.exceptions.RequestException as e:
print(f"リクエスト例外: {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"API レスポンス内容: {content}")
# 画像リンクを抽出
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"画像リンクを発見: {found_links}")
else:
result["success"] = True
result["note"] = "API はテキスト説明を返しました。画像リンクは見つかりませんでした"
except Exception as e:
result["error"] = f"レスポンス処理に失敗: {e}"
return result
def main():
print("🎨 画像生成スクリプト")
print("-" * 50)
generator = ImageGenerator()
prompt = "庭で遊んでいるかわいい子犬" # ここの prompt 内容を変更
result = generator.generate_image(prompt=prompt, save_dir="./test_images")
print("\n" + "=" * 50)
if result.get("success", False):
print("✅ リクエスト成功!")
if result.get("image_links"):
print(f"\n📷 {len(result['image_links'])} 個の画像リンクを発見:")
for i, link in enumerate(result["image_links"], 1):
print(f" {i}. {link}")
else:
print(f"❌ 生成に失敗: {result.get('error', '不明なエラー')}")
if __name__ == "__main__":
main()
画像認識 画像を送信する必要がある場合は、モデル gpt-5.4 を使用し、標準の OpenAI Vision 形式を参照してください。
