File size: 4,942 Bytes
44a2550 a5359f9 44a2550 a5359f9 44a2550 6293e69 |
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 |
/**
* API client for Rescored backend.
*/
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
const WS_BASE_URL = API_BASE_URL.replace('http', 'ws');
export interface TranscribeRequest {
youtube_url: string;
options?: {
instruments: string[];
};
}
export interface TranscribeResponse {
job_id: string;
status: string;
created_at: string;
estimated_duration_seconds: number;
websocket_url: string;
}
export interface JobStatus {
job_id: string;
status: 'queued' | 'processing' | 'completed' | 'failed';
progress: number;
current_stage: string | null;
status_message: string | null;
created_at: string;
started_at: string | null;
completed_at: string | null;
failed_at: string | null;
error: { message: string; retryable: boolean } | null;
result_url: string | null;
}
export interface ProgressUpdate {
type: 'progress' | 'completed' | 'error' | 'heartbeat';
job_id: string;
progress?: number;
stage?: string;
message?: string;
result_url?: string;
error?: { message: string; retryable: boolean };
timestamp: string;
}
export class RescoredAPI {
private baseURL = API_BASE_URL;
private wsBaseURL = WS_BASE_URL;
async submitJob(youtubeURL: string, options?: { instruments?: string[]; vocalInstrument?: number }): Promise<TranscribeResponse> {
const response = await fetch(`${this.baseURL}/api/v1/transcribe`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
youtube_url: youtubeURL,
options: options ?? { instruments: ['piano'] },
}),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to submit job');
}
return response.json();
}
async submitFileJob(file: File, options?: { instruments?: string[]; vocalInstrument?: number }): Promise<TranscribeResponse> {
const formData = new FormData();
formData.append('file', file);
formData.append('instruments', JSON.stringify(options?.instruments ?? ['piano']));
if (options?.vocalInstrument !== undefined) {
formData.append('vocal_instrument', options.vocalInstrument.toString());
}
const response = await fetch(`${this.baseURL}/api/v1/transcribe/upload`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to submit file');
}
return response.json();
}
async getJobStatus(jobId: string): Promise<JobStatus> {
const response = await fetch(`${this.baseURL}/api/v1/jobs/${jobId}`);
if (!response.ok) {
throw new Error('Failed to fetch job status');
}
return response.json();
}
async getScore(jobId: string): Promise<string> {
const response = await fetch(`${this.baseURL}/api/v1/scores/${jobId}`);
if (!response.ok) {
throw new Error('Failed to fetch score');
}
return response.text();
}
connectWebSocket(
jobId: string,
onMessage: (update: ProgressUpdate) => void,
onError?: (error: Event) => void,
onClose?: () => void
): WebSocket {
const ws = new WebSocket(`${this.wsBaseURL}/api/v1/jobs/${jobId}/stream`);
ws.onmessage = (event) => {
const update: ProgressUpdate = JSON.parse(event.data);
onMessage(update);
// Send pong for heartbeat
if (update.type === 'heartbeat') {
ws.send(JSON.stringify({ type: 'pong', timestamp: new Date().toISOString() }));
}
};
if (onError) {
ws.onerror = onError;
}
if (onClose) {
ws.onclose = onClose;
}
return ws;
}
getScoreURL(jobId: string): string {
return `${this.baseURL}/api/v1/scores/${jobId}`;
}
}
export const api = new RescoredAPI();
// Compatibility function wrappers for tests
export async function submitTranscription(
youtubeURL: string,
options?: { instruments?: string[] }
) {
// Delegate to class method; include options if provided
return api.submitJob(youtubeURL, options);
}
export async function getJobStatus(jobId: string) {
return api.getJobStatus(jobId);
}
export async function downloadScore(jobId: string) {
return api.getScore(jobId);
}
export async function getMidiFile(jobId: string): Promise<ArrayBuffer> {
const response = await fetch(`${API_BASE_URL}/api/v1/scores/${jobId}/midi`);
if (!response.ok) {
throw new Error('Failed to fetch MIDI file');
}
return response.arrayBuffer();
}
export interface ScoreMetadata {
tempo: number;
key_signature: string;
time_signature: { numerator: number; denominator: number };
}
export async function getMetadata(jobId: string): Promise<ScoreMetadata> {
const response = await fetch(`${API_BASE_URL}/api/v1/scores/${jobId}/metadata`);
if (!response.ok) {
throw new Error('Failed to fetch metadata');
}
return response.json();
}
|