File size: 6,012 Bytes
320a9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1947d7
320a9c2
 
a1947d7
69524c2
320a9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
 
3446868
 
 
 
649bebb
3446868
69524c2
 
 
 
3446868
69524c2
 
 
320a9c2
69524c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a9c2
69524c2
 
 
 
320a9c2
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
// Helper to check if the current hostname is a local loopback or private network address
const isLocalHost = () => {
  const hostname = window.location.hostname;
  return (
    hostname === 'localhost' ||
    hostname === '127.0.0.1' ||
    hostname === '[::1]' ||
    // Private IPv4 ranges (RFC 1918)
    /^192\.168\./.test(hostname) ||
    /^10\./.test(hostname) ||
    /^172\.(1[6-9]|2\d|3[01])\./.test(hostname) ||
    // mDNS local hostnames
    /\.local$/.test(hostname)
  );
};

// Dynamic backend URL to support local development and production Hugging Face Space
const BASE_URL = isLocalHost()
  ? `http://${window.location.hostname}:8001`
  : 'https://jenishmakwana-rag.hf.space';

// Helper to parse error details and attach status code
async function handleResponseError(response, defaultMsg) {
  let errorMsg = defaultMsg;
  try {
    const errorData = await response.json();
    errorMsg = errorData.detail || errorMsg;
  } catch (e) {
    // Ignore JSON parsing errors for non-JSON responses
  }
  const err = new Error(errorMsg);
  err.status = response.status;
  throw err;
}

export async function login(email, password) {
  const formData = new URLSearchParams();
  formData.append('username', email); // OAuth2 expects 'username' field
  formData.append('password', password);

  const response = await fetch(`${BASE_URL}/token`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: formData,
  });

  if (!response.ok) {
    await handleResponseError(response, 'Login failed');
  }

  return await response.json();
}

export async function register(username, email, password) {
  const response = await fetch(`${BASE_URL}/register`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ username, email, password }),
  });

  if (!response.ok) {
    await handleResponseError(response, 'Registration failed');
  }

  return await response.json();
}

export async function fetchDocuments(token) {
  const response = await fetch(`${BASE_URL}/documents/`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    await handleResponseError(response, 'Failed to fetch documents');
  }

  return await response.json();
}

export async function uploadDocument(token, file, sessionId = null) {
  const formData = new FormData();
  formData.append('file', file);
  if (sessionId) {
    formData.append('session_id', sessionId);
  }

  const response = await fetch(`${BASE_URL}/documents/upload`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
    },
    body: formData,
  });

  if (!response.ok) {
    await handleResponseError(response, 'Upload failed');
  }

  return await response.json();
}

export async function deleteDocument(token, filename) {
  const response = await fetch(`${BASE_URL}/documents/${encodeURIComponent(filename)}`, {
    method: 'DELETE',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    await handleResponseError(response, 'Delete failed');
  }

  return await response.json();
}

export async function chatQuery(token, query, sessionId, filename = null, filenames = null) {
  const response = await fetch(`${BASE_URL}/chat/`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({
      query,
      session_id: sessionId,
      filename,
      filenames
    }),
  });

  if (!response.ok) {
    await handleResponseError(response, 'Chat query failed');
  }

  // Return the raw response so the UI can read the stream
  return response;
}

export async function fetchChatSessions(token) {
  const response = await fetch(`${BASE_URL}/chat/sessions`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    await handleResponseError(response, 'Failed to fetch chat sessions');
  }

  return await response.json();
}

export async function fetchChatHistory(token, sessionId) {
  const response = await fetch(`${BASE_URL}/chat/history/${sessionId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    await handleResponseError(response, 'Failed to fetch chat history');
  }

  return await response.json();
}

export async function fetchSessionDocuments(token, sessionId) {
  const response = await fetch(`${BASE_URL}/documents/session/${sessionId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    await handleResponseError(response, 'Failed to fetch session documents');
  }

  return await response.json();
}

export async function deleteChatSession(token, sessionId) {
  const response = await fetch(`${BASE_URL}/chat/session/${sessionId}`, {
    method: 'DELETE',
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    await handleResponseError(response, 'Failed to delete chat session');
  }

  return await response.json();
}

export async function transcribeVoice(token, audioBlob) {
  const formData = new FormData();
  // Name the file 'recording.webm' so backend knows how to save it
  formData.append('file', audioBlob, 'recording.webm');

  const response = await fetch(`${BASE_URL}/voice/transcribe`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
    },
    body: formData,
  });

  if (!response.ok) {
    await handleResponseError(response, 'Failed to transcribe audio');
  }

  return await response.json();
}

export async function getTtsAudio(token, text, signal) {
  const response = await fetch(`${BASE_URL}/chat/speak`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ text }),
    signal
  });

  if (!response.ok) {
    await handleResponseError(response, 'TTS request failed');
  }

  return response;
}