File size: 6,660 Bytes
6cdce85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { DatasetExample, TaskType, Category, CodingProblem } from '@/types';

interface HFImage {
  src: string;
  height: number;
  width: number;
}

interface HFDatasetRow {
  question: string;
  answer: string;
  type: string;
  category: string;
  image: HFImage | null;
  test_code: string | null;
  entry_point: string | null;
  source: string;
}

interface HFDatasetResponse {
  rows: Array<{ row: HFDatasetRow; row_idx: number }>;
  num_rows_total: number;
}

interface HFSplitInfo {
  num_examples: number;
}

interface HFDatasetInfo {
  dataset_info?: {
    default?: {
      splits?: Record<string, HFSplitInfo>;
    };
  };
}

export interface LoadExamplesResult {
  examples: DatasetExample[];
  total: number;
}

export interface FilterOptions {
  type?: TaskType;
  category?: Category;
  hasImage?: boolean;
  search?: string;
  codingOnly?: boolean;
}

const HF_DATASET_API = 'https://datasets-server.huggingface.co';
const DATASET_ID = 'samuellimabraz/quantum-assistant';
const MAX_FETCH_LIMIT = 100;

export class DatasetLoader {
  private splitData: Map<string, DatasetExample[]> = new Map();
  private splitInfo: Record<string, number> = {};
  private isLoading: Map<string, Promise<void>> = new Map();

  /**
   * Preload all examples for a split (fetches all data at once)
   */
  async preloadSplit(split: 'train' | 'validation' | 'test'): Promise<void> {
    if (this.splitData.has(split)) {
      return;
    }

    // Prevent duplicate loading
    if (this.isLoading.has(split)) {
      return this.isLoading.get(split);
    }

    const loadPromise = this.fetchAllExamples(split);
    this.isLoading.set(split, loadPromise);

    try {
      await loadPromise;
    } finally {
      this.isLoading.delete(split);
    }
  }

  private async fetchAllExamples(split: 'train' | 'validation' | 'test'): Promise<void> {
    const allExamples: DatasetExample[] = [];
    let offset = 0;
    let total = 0;

    // First request to get total count
    const firstBatch = await this.fetchBatch(split, 0, MAX_FETCH_LIMIT);
    allExamples.push(...firstBatch.examples);
    total = firstBatch.total;
    offset = firstBatch.examples.length;

    // Fetch remaining batches
    while (offset < total) {
      const batch = await this.fetchBatch(split, offset, MAX_FETCH_LIMIT);
      allExamples.push(...batch.examples);
      offset += batch.examples.length;

      if (batch.examples.length < MAX_FETCH_LIMIT) break;
    }

    this.splitData.set(split, allExamples);
    this.splitInfo[split] = allExamples.length;
  }

  private async fetchBatch(
    split: string,
    offset: number,
    limit: number
  ): Promise<{ examples: DatasetExample[]; total: number }> {
    const url = `${HF_DATASET_API}/rows?dataset=${encodeURIComponent(DATASET_ID)}&config=default&split=${split}&offset=${offset}&length=${limit}`;

    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Failed to load dataset: ${response.status}`);
    }

    const data: HFDatasetResponse = await response.json();

    const examples: DatasetExample[] = data.rows.map((item) => {
      const row = item.row;
      return {
        id: `${split}-${item.row_idx}`,
        question: row.question,
        answer: row.answer,
        type: row.type as TaskType,
        category: row.category as Category,
        imageUrl: row.image?.src || undefined,
        hasImage: row.image !== null,
        testCode: row.test_code || undefined,
        entryPoint: row.entry_point || undefined,
        source: row.source,
      };
    });

    return { examples, total: data.num_rows_total };
  }

  /**
   * Check if a split is loaded
   */
  isLoaded(split: 'train' | 'validation' | 'test'): boolean {
    return this.splitData.has(split);
  }

  /**
   * Get loading progress (for UI feedback)
   */
  isCurrentlyLoading(split: 'train' | 'validation' | 'test'): boolean {
    return this.isLoading.has(split);
  }

  /**
   * Get all examples for a split (must be preloaded first)
   */
  getAllExamples(split: 'train' | 'validation' | 'test'): DatasetExample[] {
    return this.splitData.get(split) || [];
  }

  /**
   * Get coding problems from loaded data
   */
  getCodingProblems(split: 'train' | 'validation' | 'test'): CodingProblem[] {
    const examples = this.splitData.get(split) || [];
    return examples.filter(
      (e): e is CodingProblem =>
        e.testCode !== undefined &&
        e.entryPoint !== undefined &&
        (e.type === 'function_completion' || e.type === 'code_generation')
    );
  }

  /**
   * Filter and paginate locally loaded data
   */
  filterExamples(
    split: 'train' | 'validation' | 'test',
    filters: FilterOptions,
    limit: number = 50,
    offset: number = 0
  ): LoadExamplesResult {
    let examples = filters.codingOnly
      ? this.getCodingProblems(split)
      : this.getAllExamples(split);

    // Apply filters
    if (filters.type) {
      examples = examples.filter((e) => e.type === filters.type);
    }
    if (filters.category) {
      examples = examples.filter((e) => e.category === filters.category);
    }
    if (filters.hasImage !== undefined) {
      examples = examples.filter((e) => e.hasImage === filters.hasImage);
    }
    if (filters.search) {
      const searchLower = filters.search.toLowerCase();
      examples = examples.filter(
        (e) =>
          e.question.toLowerCase().includes(searchLower) ||
          e.answer.toLowerCase().includes(searchLower)
      );
    }

    const total = examples.length;
    const paginated = examples.slice(offset, offset + limit);

    return { examples: paginated, total };
  }

  /**
   * Get split information
   */
  async getSplitInfo(): Promise<Record<string, number>> {
    // Return cached if available
    if (Object.keys(this.splitInfo).length > 0) {
      return this.splitInfo;
    }

    const url = `${HF_DATASET_API}/info?dataset=${encodeURIComponent(DATASET_ID)}`;

    try {
      const response = await fetch(url);
      if (!response.ok) {
        return { train: 8366, validation: 1247, test: 1291 };
      }

      const data: HFDatasetInfo = await response.json();
      const splits = data.dataset_info?.default?.splits || {};

      const result: Record<string, number> = {};
      for (const [name, info] of Object.entries(splits)) {
        result[name] = info.num_examples || 0;
      }

      this.splitInfo = result;
      return result;
    } catch {
      return { train: 8366, validation: 1247, test: 1291 };
    }
  }

  /**
   * Clear cache
   */
  clearCache(): void {
    this.splitData.clear();
    this.splitInfo = {};
  }
}

export const datasetLoader = new DatasetLoader();