File size: 2,398 Bytes
e7abd9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Utility function to detect if a string looks like a regex
export const looksLikeRegex = (str) => {
  const regexSpecialChars = /[\\^$.*+?()[\]{}|]/;
  return regexSpecialChars.test(str);
};

// Function to map search fields to correct paths
const getFieldPath = (field) => {
  const fieldMappings = {
    precision: "model.precision",
    architecture: "model.architecture",
    license: "metadata.hub_license",
    type: "model.type",
  };
  return fieldMappings[field] || field;
};

// Function to extract special searches and normal text
export const parseSearchQuery = (query) => {
  const specialSearches = [];
  let remainingText = query;

  // Look for all @field:value patterns
  const prefixRegex = /@\w+:/g;
  const matches = query.match(prefixRegex) || [];

  matches.forEach((prefix) => {
    const regex = new RegExp(`${prefix}([^\\s@]+)`, "g");
    remainingText = remainingText.replace(regex, (match, value) => {
      const field = prefix.slice(1, -1);
      specialSearches.push({
        field: getFieldPath(field),
        displayField: field,
        value,
      });
      return "";
    });
  });

  return {
    specialSearches,
    textSearch: remainingText.trim(),
  };
};

// Function to extract simple text search
export const extractTextSearch = (searchValue) => {
  return searchValue
    .split(";")
    .map((query) => {
      const { textSearch } = parseSearchQuery(query);
      return textSearch;
    })
    .filter(Boolean)
    .join(";");
};

// Utility function to access nested object properties
export const getValueByPath = (obj, path) => {
  return path.split(".").reduce((acc, part) => acc?.[part], obj);
};

// Function to generate natural language description of the search
export const generateSearchDescription = (searchValue) => {
  if (!searchValue) return null;

  const searchGroups = searchValue
    .split(";")
    .map((group) => group.trim())
    .filter(Boolean);

  return searchGroups.map((group, index) => {
    const { specialSearches, textSearch } = parseSearchQuery(group);

    let parts = [];
    if (textSearch) {
      parts.push(textSearch);
    }

    if (specialSearches.length > 0) {
      const specialParts = specialSearches.map(
        ({ displayField, value }) => `@${displayField}:${value}`
      );
      parts = parts.concat(specialParts);
    }

    return {
      text: parts.join(" "),
      index,
    };
  });
};