File size: 6,386 Bytes
565e57b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { PicletInstance, DiscoveryStatus } from '$lib/db/schema';

const SERVER_URL = import.meta.env.DEV
  ? 'http://localhost:3000'
  : 'https://piclets-server.herokuapp.com';

export interface CanonicalSearchResult {
  status: DiscoveryStatus;
  piclet: PicletInstance;
  canonicalId?: string;
  matchedAttributes?: string[];
  suggestedVariation?: string[];
}

export interface ObjectExtractionResult {
  primaryObject: string;
  attributes: string[];
  visualDetails: string;
}

export class CanonicalService {
  /**
   * Extract object and attributes from image caption
   * Focuses on identifying the primary object and its variations
   */
  static extractObjectFromCaption(caption: string): ObjectExtractionResult {
    // Clean and normalize caption
    const normalized = caption.toLowerCase().trim();

    // Common patterns to identify the main object
    // Priority: noun after article (a/an/the), first noun, or key noun phrases
    const objectPatterns = [
      /(?:a|an|the)\s+(\w+(?:\s+\w+)?)\s+(?:is|sits|stands|lies|rests)/i,
      /(?:a|an|the)\s+([\w\s]+?)(?:\s+with|\s+that|\s+in|\s+on|,|\.|$)/i,
      /^([\w\s]+?)(?:\s+with|\s+that|\s+in|\s+on|,|\.|$)/i,
    ];

    let primaryObject = '';
    for (const pattern of objectPatterns) {
      const match = caption.match(pattern);
      if (match && match[1]) {
        // Clean up the captured object
        primaryObject = match[1]
          .trim()
          .replace(/\s+/g, ' ')
          .split(' ')
          .filter(word => !['very', 'quite', 'rather', 'extremely'].includes(word))
          .pop() || ''; // Get the last word as the core object

        if (primaryObject) break;
      }
    }

    // Fallback: take first noun-like word
    if (!primaryObject) {
      const words = normalized.split(/\s+/);
      primaryObject = words.find(w => w.length > 3 && !['with', 'that', 'this', 'from'].includes(w)) || 'object';
    }

    // Extract descriptive attributes (limit to 2-3 most relevant)
    const attributeWords = [
      // Materials
      'wooden', 'metal', 'plastic', 'glass', 'leather', 'velvet', 'silk', 'cotton', 'stone', 'marble',
      'gold', 'silver', 'bronze', 'copper', 'steel', 'iron', 'aluminum', 'ceramic', 'porcelain',
      // Styles
      'modern', 'vintage', 'antique', 'rustic', 'minimalist', 'ornate', 'gothic', 'art deco', 'retro',
      // Colors (basic only)
      'red', 'blue', 'green', 'yellow', 'purple', 'orange', 'black', 'white', 'gray', 'brown',
      // Patterns
      'striped', 'polka dot', 'floral', 'geometric', 'plaid', 'checkered',
      // Conditions
      'old', 'new', 'worn', 'shiny', 'matte', 'glossy', 'rough', 'smooth'
    ];

    const attributes: string[] = [];
    const lowerCaption = caption.toLowerCase();

    for (const attr of attributeWords) {
      if (lowerCaption.includes(attr) && attributes.length < 3) {
        attributes.push(attr);
      }
    }

    // Extract visual details for monster generation (everything else interesting)
    const visualDetails = caption
      .replace(new RegExp(primaryObject, 'gi'), '')
      .replace(new RegExp(attributes.join('|'), 'gi'), '')
      .replace(/(?:a|an|the)\s+/gi, '')
      .replace(/\s+/g, ' ')
      .trim();

    return {
      primaryObject: primaryObject.toLowerCase(),
      attributes,
      visualDetails
    };
  }

  /**
   * Search for canonical Piclet or variations
   */
  static async searchCanonical(
    objectName: string,
    attributes: string[]
  ): Promise<CanonicalSearchResult | null> {
    try {
      const response = await fetch(`${SERVER_URL}/api/piclets/search`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ object: objectName, attributes })
      });

      if (!response.ok) {
        console.error('Server search failed:', response.status);
        return null;
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to search canonical:', error);
      return null;
    }
  }

  /**
   * Create a new canonical Piclet
   */
  static async createCanonical(
    piclet: Partial<PicletInstance>,
    discovererName: string
  ): Promise<PicletInstance | null> {
    try {
      const response = await fetch(`${SERVER_URL}/api/piclets/canonical`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...piclet,
          discoveredBy: discovererName,
          discoveredAt: new Date(),
          isCanonical: true,
          scanCount: 1
        })
      });

      if (!response.ok) {
        console.error('Failed to create canonical:', response.status);
        return null;
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to create canonical:', error);
      return null;
    }
  }

  /**
   * Create a variation of existing canonical Piclet
   */
  static async createVariation(
    canonicalId: string,
    variation: Partial<PicletInstance>,
    discovererName: string
  ): Promise<PicletInstance | null> {
    try {
      const response = await fetch(`${SERVER_URL}/api/piclets/variation`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          canonicalId,
          ...variation,
          discoveredBy: discovererName,
          discoveredAt: new Date(),
          isCanonical: false,
          scanCount: 1
        })
      });

      if (!response.ok) {
        console.error('Failed to create variation:', response.status);
        return null;
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to create variation:', error);
      return null;
    }
  }

  /**
   * Increment scan count for existing Piclet
   */
  static async incrementScanCount(picletId: string): Promise<void> {
    try {
      await fetch(`${SERVER_URL}/api/piclets/${picletId}/scan`, {
        method: 'POST'
      });
    } catch (error) {
      console.error('Failed to increment scan count:', error);
    }
  }

  /**
   * Calculate rarity based on scan count
   */
  static calculateRarity(scanCount: number): string {
    if (scanCount <= 5) return 'legendary';
    if (scanCount <= 20) return 'epic';
    if (scanCount <= 50) return 'rare';
    if (scanCount <= 100) return 'uncommon';
    return 'common';
  }
}