Spaces:
Running
Running
File size: 13,980 Bytes
5191cb5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
/**
* Service for interacting with OpenRouter API.
*/
const fileToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject(new Error('Failed to convert file to base64'));
}
};
reader.onerror = error => reject(error);
});
};
const extractFramesFromVideo = async (videoFile: File, numberOfFrames: number, signal?: AbortSignal): Promise<string[]> => {
return new Promise((resolve, reject) => {
const video = document.createElement('video');
video.preload = 'metadata';
video.muted = true;
video.playsInline = true;
const url = URL.createObjectURL(videoFile);
const frames: string[] = [];
const onAbort = () => {
URL.revokeObjectURL(url);
video.src = "";
reject(new Error("AbortError"));
};
if (signal) signal.addEventListener('abort', onAbort);
const timeout = setTimeout(() => {
if (signal) signal.removeEventListener('abort', onAbort);
URL.revokeObjectURL(url);
video.src = "";
reject(new Error("Video processing timed out"));
}, 60000);
video.onloadeddata = async () => {
const duration = video.duration;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
if (signal) signal.removeEventListener('abort', onAbort);
clearTimeout(timeout);
URL.revokeObjectURL(url);
reject(new Error("Could not create canvas context"));
return;
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const step = duration / numberOfFrames;
try {
for (let i = 0; i < numberOfFrames; i++) {
if (signal?.aborted) throw new Error("AbortError");
const time = (step * i) + (step / 2);
await new Promise<void>((frameResolve) => {
const onSeeked = () => {
video.removeEventListener('seeked', onSeeked);
frameResolve();
};
video.addEventListener('seeked', onSeeked);
video.currentTime = Math.min(time, duration - 0.1);
});
ctx.drawImage(video, 0, 0);
frames.push(canvas.toDataURL('image/jpeg', 0.8));
}
if (signal) signal.removeEventListener('abort', onAbort);
clearTimeout(timeout);
URL.revokeObjectURL(url);
video.src = "";
resolve(frames);
} catch (e) {
if (signal) signal.removeEventListener('abort', onAbort);
clearTimeout(timeout);
URL.revokeObjectURL(url);
reject(e);
}
};
video.onerror = () => {
if (signal) signal.removeEventListener('abort', onAbort);
clearTimeout(timeout);
URL.revokeObjectURL(url);
reject(new Error("Failed to load video file"));
};
video.src = url;
});
};
const constructPrompt = (
triggerWord: string,
customInstructions?: string,
isCharacterTaggingEnabled?: boolean,
characterShowName?: string
): string => {
let basePrompt = `You are an expert captioner for AI model training data. Your task is to describe the provided image/video in detail for a style LoRA. Follow these rules strictly:
1. Start the caption with the trigger word: "${triggerWord}".
2. Describe EVERYTHING visible: characters, clothing, actions, background, objects, lighting, and camera angle.
3. Be objective and factual.
4. DO NOT mention art styles or generic animation terms like "anime" or "cartoon".
5. Write as a single, continuous paragraph.`;
if (isCharacterTaggingEnabled && characterShowName && characterShowName.trim() !== '') {
basePrompt += `\n6. Identify characters from the show/series "${characterShowName}" and append tags at the end of the caption, separated by commas. The format for each tag must be "char_[charactername]" (e.g., ", char_simon, char_kamina"). If no characters are recognized, do not add tags.`;
}
if (customInstructions) {
return `${basePrompt}\n\nAdditional instructions: ${customInstructions}`;
}
return basePrompt;
};
export const generateCaptionOpenRouter = async (
apiKey: string,
model: string,
file: File,
triggerWord: string,
customInstructions?: string,
isCharacterTaggingEnabled?: boolean,
characterShowName?: string,
videoFrameCount: number = 8,
maxTokens: number = 4096,
temperature: number = 0.7,
useFullVideo: boolean = false,
signal?: AbortSignal
): Promise<string> => {
if (!apiKey) throw new Error("OpenRouter API Key is required.");
const endpoint = 'https://openrouter.ai/api/v1/chat/completions';
const prompt = constructPrompt(triggerWord, customInstructions, isCharacterTaggingEnabled, characterShowName);
// Extract model ID from URL if provided
let modelId = model.includes('openrouter.ai/') ? model.split('openrouter.ai/').pop() || '' : model;
// Handle /models/ prefix if it exists in the URL
if (modelId.startsWith('models/')) {
modelId = modelId.replace('models/', '');
}
// Remove any trailing slashes or query params
modelId = modelId.split('?')[0].replace(/\/+$/, '');
let contentParts: any[] = [{ type: "text", text: prompt }];
if (file.type.startsWith('video/')) {
if (useFullVideo) {
const base64Video = await fileToBase64(file);
contentParts.push({ type: "image_url", image_url: { url: base64Video } });
} else {
const frames = await extractFramesFromVideo(file, videoFrameCount, signal);
frames.forEach(frame => contentParts.push({ type: "image_url", image_url: { url: frame } }));
}
} else {
const base64Image = await fileToBase64(file);
contentParts.push({ type: "image_url", image_url: { url: base64Image } });
}
const payload = {
model: modelId || 'openai/gpt-4o-mini',
messages: [{ role: "user", content: contentParts }],
max_tokens: maxTokens,
temperature: temperature
};
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
"HTTP-Referer": window.location.origin,
"X-Title": "LoRA Caption Assistant"
},
body: JSON.stringify(payload),
signal
});
if (!response.ok) {
let errorMessage = response.statusText;
try {
const errData = await response.json();
errorMessage = errData.error?.message || errData.message || JSON.stringify(errData) || errorMessage;
} catch (e) {
const errText = await response.text().catch(() => "");
if (errText) errorMessage = errText;
}
throw new Error(`OpenRouter API Error (${response.status}): ${errorMessage}`);
}
const data = await response.json();
console.log('OpenRouter Generate Response:', data);
const message = data.choices?.[0]?.message;
let content = "";
if (message) {
if (typeof message.content === 'string') {
content = message.content.trim();
} else if (Array.isArray(message.content)) {
// Handle cases where content might be returned as an array of parts
content = message.content
.filter((part: any) => part.type === 'text')
.map((part: any) => part.text)
.join('\n')
.trim();
}
}
const refusal = message?.refusal;
const reasoning = message?.reasoning;
const finishReason = data.choices?.[0]?.finish_reason;
if (!content && refusal) {
throw new Error(`OpenRouter Refusal: ${refusal}`);
}
if (!content && finishReason === 'length') {
if (reasoning) {
// If we only have reasoning and it hit the length limit, the model likely
// spent all tokens "thinking" and never got to the output.
throw new Error("OpenRouter model hit token limit during reasoning. Try increasing max tokens or using a non-reasoning model.");
}
throw new Error("OpenRouter response was cut off (hit token limit).");
}
if (!content && finishReason === 'content_filter') {
throw new Error("OpenRouter response was blocked by content filter.");
}
// Some models might put the result in reasoning if content is null,
// though rare for standard chat completions.
return content || (reasoning ? `[Reasoning Only]: ${reasoning}` : "");
};
export const refineCaptionOpenRouter = async (
apiKey: string,
model: string,
file: File,
currentCaption: string,
refinementInstructions: string,
videoFrameCount: number = 4,
maxTokens: number = 4096,
temperature: number = 0.7,
useFullVideo: boolean = false,
signal?: AbortSignal
): Promise<string> => {
if (!apiKey) throw new Error("OpenRouter API Key is required.");
const endpoint = 'https://openrouter.ai/api/v1/chat/completions';
const prompt = `Refine the following caption based on the visual information and the instructions. Output ONLY the refined text.
CURRENT CAPTION: "${currentCaption}"
INSTRUCTIONS: "${refinementInstructions}"`;
let modelId = model.includes('openrouter.ai/') ? model.split('openrouter.ai/').pop() || '' : model;
if (modelId.startsWith('models/')) modelId = modelId.replace('models/', '');
modelId = modelId.split('?')[0].replace(/\/+$/, '');
let contentParts: any[] = [{ type: "text", text: prompt }];
if (file.type.startsWith('video/')) {
if (useFullVideo) {
const base64Video = await fileToBase64(file);
contentParts.push({ type: "image_url", image_url: { url: base64Video } });
} else {
const frames = await extractFramesFromVideo(file, videoFrameCount, signal);
frames.forEach(frame => contentParts.push({ type: "image_url", image_url: { url: frame } }));
}
} else {
const base64Image = await fileToBase64(file);
contentParts.push({ type: "image_url", image_url: { url: base64Image } });
}
const payload = {
model: modelId || 'openai/gpt-4o-mini',
messages: [{ role: "user", content: contentParts }],
max_tokens: maxTokens,
temperature: temperature
};
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
"HTTP-Referer": window.location.origin,
"X-Title": "LoRA Caption Assistant"
},
body: JSON.stringify(payload),
signal
});
if (!response.ok) {
let errorMessage = response.statusText;
try {
const errData = await response.json();
errorMessage = errData.error?.message || errData.message || JSON.stringify(errData) || errorMessage;
} catch (e) {
const errText = await response.text().catch(() => "");
if (errText) errorMessage = errText;
}
throw new Error(`OpenRouter API Error (${response.status}): ${errorMessage}`);
}
const data = await response.json();
console.log('OpenRouter Refine Response:', data);
const content = data.choices?.[0]?.message?.content?.trim();
const refusal = data.choices?.[0]?.message?.refusal;
if (!content && refusal) throw new Error(`OpenRouter Refusal: ${refusal}`);
return content || "";
};
export const checkQualityOpenRouter = async (
apiKey: string,
model: string,
file: File,
caption: string,
videoFrameCount: number = 4,
temperature: number = 0.7,
useFullVideo: boolean = false,
signal?: AbortSignal
): Promise<number> => {
if (!apiKey) throw new Error("OpenRouter API Key is required.");
const endpoint = 'https://openrouter.ai/api/v1/chat/completions';
const prompt = `Evaluate the caption quality. Respond with ONLY an integer from 1 to 5.\nCaption: "${caption}"`;
let modelId = model.includes('openrouter.ai/') ? model.split('openrouter.ai/').pop() || '' : model;
if (modelId.startsWith('models/')) modelId = modelId.replace('models/', '');
modelId = modelId.split('?')[0].replace(/\/+$/, '');
let contentParts: any[] = [{ type: "text", text: prompt }];
if (file.type.startsWith('video/')) {
if (useFullVideo) {
const base64Video = await fileToBase64(file);
contentParts.push({ type: "image_url", image_url: { url: base64Video } });
} else {
const frames = await extractFramesFromVideo(file, videoFrameCount, signal);
frames.forEach(frame => contentParts.push({ type: "image_url", image_url: { url: frame } }));
}
} else {
const base64Image = await fileToBase64(file);
contentParts.push({ type: "image_url", image_url: { url: base64Image } });
}
const payload = {
model: modelId || 'openai/gpt-4o-mini',
messages: [{ role: "user", content: contentParts }],
max_tokens: 10,
temperature: temperature
};
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
"HTTP-Referer": window.location.origin,
"X-Title": "LoRA Caption Assistant"
},
body: JSON.stringify(payload),
signal
});
if (!response.ok) {
let errorMessage = response.statusText;
try {
const errData = await response.json();
errorMessage = errData.error?.message || errData.message || JSON.stringify(errData) || errorMessage;
} catch (e) {
const errText = await response.text().catch(() => "");
if (errText) errorMessage = errText;
}
throw new Error(`OpenRouter API Error (${response.status}): ${errorMessage}`);
}
const data = await response.json();
console.log('OpenRouter Quality Response:', data);
const text = data.choices?.[0]?.message?.content?.trim();
const refusal = data.choices?.[0]?.message?.refusal;
if (!text && refusal) throw new Error(`OpenRouter Refusal: ${refusal}`);
return parseInt(text?.match(/\d+/)?.[0] || '0', 10);
};
|