File size: 2,580 Bytes
911f7e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* PDF extraction uses HTTP. Model calls use the official Gradio queue client
   so Hugging Face can apply each visitor's ZeroGPU quota. */
(function () {
  'use strict';
  let clientPromise;

  function getClient() {
    if (!clientPromise) {
      clientPromise = import('./gradio-client.mjs')
        .then(({Client}) => Client.connect(window.location.origin))
        .catch(error => { clientPromise = undefined; throw error; });
    }
    return clientPromise;
  }

  async function http(path, options = {}) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 60000);
    try {
      const response = await fetch(path, {...options, signal: controller.signal});
      const body = await response.json();
      if (!response.ok) throw new Error(typeof body.detail === 'string' ? body.detail : '服务暂时无法处理这次请求。');
      return body;
    } catch (error) {
      if (error.name === 'AbortError') throw new Error('请求超时,请重试。');
      if (error instanceof TypeError) throw new Error('无法连接面试服务,请检查网络。');
      throw error;
    } finally {
      clearTimeout(timer);
    }
  }

  async function predict(endpoint, payload) {
    let response;
    try {
      const client = await getClient();
      response = await client.predict(endpoint, [payload]);
    } catch (error) {
      const message = error?.message || String(error || '');
      if (/quota|exceeded.*gpu/i.test(message)) {
        throw new Error('Hugging Face 提示 GPU 配额不足。可在 Space 页面登录查看额度,或先体验功能示例。');
      }
      throw new Error(message || 'AI 服务暂时无法处理这次请求,请稍后重试。');
    }
    const result = response?.data?.[0];
    if (!result || typeof result !== 'object') throw new Error('模型返回的数据无法读取,请重试。');
    if (result.detail) throw new Error(result.detail);
    return result;
  }

  window.PracticeAPI = {
    config: async () => {
      const config = await http('/api/config');
      if (config.aiAvailable) getClient().catch(() => {});
      return config;
    },
    uploadCV: file => http('/api/cv', {
      method: 'POST', body: file,
      headers: {'Content-Type': 'application/pdf', 'X-Filename': encodeURIComponent(file.name)}
    }),
    questions: payload => predict('/questions', payload),
    followUp: payload => predict('/follow_up', payload),
    feedback: payload => predict('/feedback', payload),
    coach: payload => predict('/coach', payload)
  };
})();