File size: 8,149 Bytes
30d88bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
254
255
256
257
258
259
260
import dotenv from 'dotenv';
import express from 'express';
import { readFile } from 'node:fs/promises';
import { readdirSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { GoogleGenAI } from '@google/genai';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

dotenv.config({ path: path.join(__dirname, 'local.env') });

const app = express();
const port = process.env.PORT || 3000;
const modelName = process.env.GEMINI_MODEL || 'gemini-2.5-flash';

app.use(express.json({ limit: '7mb' }));
app.use(express.static(path.join(__dirname, 'public')));

app.get('/api/health', (_req, res) => {
  res.json({
    ok: true,
    model: modelName,
    hasGeminiKey: Boolean(process.env.GEMINI_API_KEY)
  });
});

app.post('/api/generate', async (req, res) => {
  try {
    if (!process.env.GEMINI_API_KEY) {
      return res.status(400).json({
        error: 'Missing GEMINI_API_KEY. Add it to local.env locally and to Railway variables before deployment.'
      });
    }

    const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
    const {
      artworkName = '',
      mode = 'Beginner',
      question = '',
      image,
      useKnowledgeBase = false
    } = req.body || {};

    if (!artworkName.trim() && !question.trim() && !image?.data) {
      return res.status(400).json({ error: 'Please enter an artwork name, ask a question, or upload an image.' });
    }

    const query = [artworkName, question].filter(Boolean).join(' ');
    const context = useKnowledgeBase ? await retrieveContext(query) : '';
    const prompt = buildPrompt({ artworkName, mode, question, context, hasImage: Boolean(image?.data) });
    const contents = buildContents({ prompt, image });

    const response = await ai.models.generateContent({
      model: modelName,
      contents
    });

    res.json({
      answer: response.text,
      usedKnowledgeBase: Boolean(context),
      model: modelName
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      error: error.message || 'The model call failed. Check your API key, network, and server logs.'
    });
  }
});

app.post('/api/followup', async (req, res) => {
  try {
    if (!process.env.GEMINI_API_KEY) {
      return res.status(400).json({
        error: 'Missing GEMINI_API_KEY. Add it to local.env locally and to Railway variables before deployment.'
      });
    }

    const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
    const {
      artworkName = '',
      mode = 'Beginner',
      originalQuestion = '',
      originalAnswer = '',
      followupQuestion = '',
      image,
      useKnowledgeBase = false
    } = req.body || {};

    if (!followupQuestion.trim()) {
      return res.status(400).json({ error: 'Please enter a follow-up question.' });
    }

    if (!originalAnswer.trim()) {
      return res.status(400).json({ error: 'Please generate the main artwork explanation first.' });
    }

    const query = [artworkName, originalQuestion, followupQuestion].filter(Boolean).join(' ');
    const context = useKnowledgeBase ? await retrieveContext(query) : '';
    const prompt = buildFollowupPrompt({
      artworkName,
      mode,
      originalQuestion,
      originalAnswer,
      followupQuestion,
      context,
      hasImage: Boolean(image?.data)
    });
    const contents = buildContents({ prompt, image });

    const response = await ai.models.generateContent({
      model: modelName,
      contents
    });

    res.json({
      answer: response.text,
      usedKnowledgeBase: Boolean(context),
      model: modelName
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      error: error.message || 'The follow-up model call failed. Check your API key, network, and server logs.'
    });
  }
});

function buildPrompt({ artworkName, mode, question, context, hasImage }) {
  const sourceBlock = context
    ? `Use this source material when it is relevant. If it conflicts with the visible artwork or widely known art history, explain the uncertainty simply.\\n\\nSOURCE MATERIAL:\\n${context}\\n\\n`
    : '';
  const systemPrompt = `You are Explain Art to Me, an empathetic art guide for people without formal art training.

Your job is to explain artwork in simple, friendly, emotionally relatable language. Avoid unnecessary art jargon. If a technical term is useful, define it in plain English. Do not pretend to know facts that are uncertain; say when you are making a careful guess from the image or title. Keep the first explanation warm but fairly compact so it is easy to scan.

Explanation mode: ${mode}
Artwork title or clue: ${artworkName || hasImage ? artworkName || 'Uploaded image' : 'Not provided'}`;

  return `${sourceBlock}${systemPrompt}

User question:
${question || 'Explain this artwork in a friendly way.'}

Respond with:
1. Artist in brief
2. What you are looking at
3. Emotions and symbols
4. Why it is famous
5. Personal or historical context

Use plain text section labels exactly like "Artist in brief:" without Markdown heading marks, asterisks, or bullet symbols.
Keep each section to 2 or 3 concise sentences.
End with one short line that helps the user look at the artwork again with fresh eyes.`;
}

function buildFollowupPrompt({
  artworkName,
  mode,
  originalQuestion,
  originalAnswer,
  followupQuestion,
  context,
  hasImage
}) {
  const sourceBlock = context
    ? `Use this source material when it is relevant. If it conflicts with the visible artwork, the previous answer, or widely known art history, explain the uncertainty simply.\\n\\nSOURCE MATERIAL:\\n${context}\\n\\n`
    : '';

  return `${sourceBlock}You are Explain Art to Me, an empathetic art guide for people without formal art training.

Continue the same simple, friendly, emotionally relatable tone from the initial explanation. Answer the user's follow-up as part of an art conversation. Avoid unnecessary art jargon. If a technical term is useful, define it in plain English. If the answer is uncertain, say so gently.

Explanation mode: ${mode}
Artwork title or clue: ${artworkName || hasImage ? artworkName || 'Uploaded image' : 'Not provided'}

Original user question:
${originalQuestion || 'Explain this artwork in a friendly way.'}

Initial explanation:
${originalAnswer}

Follow-up question:
${followupQuestion}

Respond with a focused answer to the follow-up question in 2 to 4 short paragraphs. Use plain text only, without Markdown heading marks, asterisks, or bullet symbols.`;
}

function buildContents({ prompt, image }) {
  if (!image?.data || !image?.mimeType) return prompt;

  return [
    {
      role: 'user',
      parts: [
        { text: prompt },
        {
          inlineData: {
            mimeType: image.mimeType,
            data: image.data
          }
        }
      ]
    }
  ];
}

async function retrieveContext(query) {
  const docsDir = path.join(__dirname, 'docs');
  if (!existsSync(docsDir)) return '';

  const files = readdirSync(docsDir).filter((name) => /\\.(md|txt)$/i.test(name));
  const chunks = [];

  for (const file of files) {
    const text = await readFile(path.join(docsDir, file), 'utf8');
    for (const chunk of chunkText(text)) {
      chunks.push({ file, chunk, score: scoreChunk(query, chunk) });
    }
  }

  return chunks
    .filter((item) => item.score > 0)
    .sort((a, b) => b.score - a.score)
    .slice(0, 3)
    .map((item) => `[${item.file}]\\n${item.chunk}`)
    .join('\\n\\n---\\n\\n');
}

function chunkText(text) {
  return text
    .split(/\\n\\s*\\n/g)
    .map((chunk) => chunk.trim())
    .filter(Boolean)
    .slice(0, 30);
}

function scoreChunk(query, chunk) {
  const queryTerms = new Set(
    query
      .toLowerCase()
      .split(/[^a-z0-9]+/)
      .filter((term) => term.length > 3)
  );

  if (!queryTerms.size) return 0;
  const lowerChunk = chunk.toLowerCase();
  let score = 0;
  for (const term of queryTerms) {
    if (lowerChunk.includes(term)) score += 1;
  }
  return score;
}

app.listen(port, () => {
  console.log(`App running on http://localhost:${port}`);
});