Spaces:
Running

File size: 7,232 Bytes
10dd572
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type {
  GenerateRequest,
  GenerateResponse,
  JobResult,
  ApiError,
  PromptDefaults,
  ModifyRequest,
  PromptLocale,
  ProblemFramingRequest,
  ProblemFramingResponse
} from '../../shared/types/api';
import { loadSettings } from '../storage/settings';
import { deriveSubtitleUrl, videoJobId } from '../../shared/media/subtitle-url';
import { getConnectionHeaders, withConnectionProvider } from '../../features/connection/connection-request';
import { localizeApiMessage, translate } from '../../shared/i18n/runtime';

export const API_BASE = '/api';

/** 获取或生成浏览器端唯一标识,用于隔离历史记录 */
function getClientId(): string {
  const KEY = 'manimcat_client_id';
  let id = localStorage.getItem(KEY);
  if (!id) {
    id = crypto.randomUUID();
    localStorage.setItem(KEY, id);
  }
  return id;
}

async function parseApiErrorMessage(response: Response, fallbackMessage: string): Promise<string> {
  try {
    const text = await response.text();
    if (!text) {
      return fallbackMessage;
    }

    const error = JSON.parse(text) as ApiError;
    return error.error ? localizeApiMessage(error.error) : fallbackMessage;
  } catch {
    return fallbackMessage;
  }
}

export async function modifyAnimation(request: ModifyRequest, signal?: AbortSignal): Promise<GenerateResponse> {
  const videoConfig = request.videoConfig || loadSettings().video;
  const payload = withConnectionProvider({ ...request, videoConfig });

  const response = await fetch(`${API_BASE}/modify`, {
    method: 'POST',
    headers: { ...getConnectionHeaders('application/json'), 'x-client-id': getClientId() },
    body: JSON.stringify(payload),
    signal,
  });

  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, translate('api.modifyFailed')));
  }

  return response.json();
}

interface UploadReferenceImageResponse {
  success: boolean;
  url: string;
  relativeUrl: string;
  mimeType: string;
  size: number;
}

export async function uploadReferenceImage(file: File, signal?: AbortSignal): Promise<UploadReferenceImageResponse> {
  const response = await fetch(`${API_BASE}/reference-images`, {
    method: 'POST',
    headers: getConnectionHeaders(file.type || 'application/octet-stream'),
    body: file,
    signal,
  });

  if (!response.ok) {
    let message = translate('api.uploadFailed');
    try {
      const error: ApiError = await response.json();
      message = error.error ? localizeApiMessage(error.error) : message;
    } catch {
      // ignore json parse errors and keep default message
    }
    throw new Error(message);
  }

  return response.json();
}

export async function generateAnimation(
  request: GenerateRequest,
  signal?: AbortSignal
): Promise<GenerateResponse> {
  const videoConfig = request.videoConfig || loadSettings().video;
  const payload = withConnectionProvider({ ...request, videoConfig });

  const response = await fetch(`${API_BASE}/generate`, {
    method: 'POST',
    headers: { ...getConnectionHeaders('application/json'), 'x-client-id': getClientId() },
    body: JSON.stringify(payload),
    signal,
  });

  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, translate('api.generateFailed')));
  }

  return response.json();
}

export async function generateProblemFraming(
  request: ProblemFramingRequest,
  signal?: AbortSignal
): Promise<ProblemFramingResponse> {
  const payload = withConnectionProvider({ ...request });

  const response = await fetch(`${API_BASE}/problem-frame`, {
    method: 'POST',
    headers: { ...getConnectionHeaders('application/json'), 'x-client-id': getClientId() },
    body: JSON.stringify(payload),
    signal,
  });

  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, translate('api.problemFramingFailed')));
  }

  const data = (await response.json()) as ProblemFramingResponse;
  if (!isUsableProblemFramingPlan(data?.plan)) {
    // The planner must return its own content. An empty plan is a failure, never a card.
    throw new Error(translate('api.problemFramingEmpty'));
  }

  return data;
}

/**
 * Shape guard for the planning card. The backend already rejects plans it would have to invent
 * (src/workflow/problem-framing/parser.ts), so this only catches drift that would render an empty card.
 */
function isUsableProblemFramingPlan(plan: ProblemFramingResponse['plan'] | undefined): boolean {
  if (!plan || typeof plan !== 'object') {
    return false;
  }
  if (!plan.headline?.trim() || !plan.summary?.trim()) {
    return false;
  }
  if (!Array.isArray(plan.steps) || plan.steps.length === 0) {
    return false;
  }
  return plan.steps.every((step) => Boolean(step?.title?.trim() && step?.content?.trim()));
}

export async function getPromptDefaults(locale?: PromptLocale, signal?: AbortSignal): Promise<PromptDefaults> {
  const query = locale ? `?locale=${encodeURIComponent(locale)}` : '';
  const response = await fetch(`${API_BASE}/prompts/defaults${query}`, {
    headers: getConnectionHeaders(),
    signal,
  });

  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, 'Failed to load prompt defaults'));
  }

  return response.json();
}

export async function getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobResult> {
  // Job status carries no provider config: it only needs identity, which the credential header gives.
  const response = await fetch(`${API_BASE}/jobs/${jobId}`, {
    headers: { ...getConnectionHeaders('application/json'), 'x-client-id': getClientId() },
    signal,
  });

  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, translate('api.jobStatusFailed')));
  }

  return response.json();
}

export async function cancelJob(jobId: string): Promise<void> {
  const response = await fetch(`${API_BASE}/jobs/${jobId}/cancel`, {
    method: 'POST',
    headers: { ...getConnectionHeaders('application/json'), 'x-client-id': getClientId() },
  });

  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, translate('api.cancelFailed')));
  }
}

/** HEAD the VTT sidecar: the web player derives it from the video URL. */
export async function hasSubtitleSidecar(videoUrl: string): Promise<boolean> {
  const subtitleUrl = deriveSubtitleUrl(videoUrl)
  if (!subtitleUrl) {
    return false;
  }
  try {
    const response = await fetch(subtitleUrl, { method: 'HEAD' });
    return response.ok;
  } catch {
    return false;
  }
}

/** Ask the backend to paint the VTT onto the picture; returns the burned MP4 URL. */
export async function requestBurnedVideo(videoUrl: string): Promise<string> {
  const jobId = videoJobId(videoUrl);
  if (!jobId) {
    throw new Error(translate('result.burnFailed'));
  }
  const response = await fetch(`${API_BASE}/videos/${encodeURIComponent(jobId)}/hardsub`, {
    method: 'POST',
    headers: { 'x-client-id': getClientId() },
  });
  if (!response.ok) {
    throw new Error(await parseApiErrorMessage(response, translate('result.burnFailed')));
  }
  const payload = (await response.json()) as { url?: unknown };
  if (typeof payload.url !== 'string' || !payload.url) {
    throw new Error(translate('result.burnFailed'));
  }
  return payload.url;
}