File size: 1,485 Bytes
47b056e
16533c4
47b056e
16533c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47b056e
16533c4
47b056e
16533c4
 
 
47b056e
 
16533c4
 
 
47b056e
16533c4
 
47b056e
16533c4
 
 
 
 
 
47b056e
16533c4
 
 
 
 
 
 
 
 
47b056e
16533c4
 
 
 
 
 
 
 
 
47b056e
16533c4
 
 
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
import { BASE_URL } from "@/utils/constants";
import type { ImageResult, AngleLabel } from "@/types";

interface RawApiResponse {
  rule_based_view_type: string[];
  review: boolean;
  final_scores: number[];
  error: string | null;
  file_details: {
    main_img_name: string;
    part_detection: string;
    car_detection: string;
  };
}

export const classifyImage = async (
  file: File
): Promise<ImageResult> => {
  const formData = new FormData();
  formData.append("files", file);

  const response = await fetch(`${BASE_URL}/api/classify-img`, {
    method: "POST",
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`API error ${response.status}: ${response.statusText}`);
  }

  const results: RawApiResponse[] = await response.json();
  const first = results[0];

  const rawError = first?.error;
  const errorMsg = rawError
    ? typeof rawError === "string"
      ? rawError
      : JSON.stringify(rawError)
    : null;

  if (!first || errorMsg) {
    return {
      filename: file.name,
      angles: [],
      scores: [],
      review: false,
      error: errorMsg ?? "Classification failed",
      fileDetails: null,
    };
  }

  return {
    filename: file.name,
    angles: (first.rule_based_view_type ?? []) as AngleLabel[],
    scores: first.final_scores ?? [],
    review: first.review ?? false,
    error: null,
    fileDetails: first.file_details ?? null,
  };
};

export const getImageUrl = (path: string) =>
  `${BASE_URL}/files/${path}`;