-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini.html
More file actions
316 lines (282 loc) · 14.9 KB
/
gemini.html
File metadata and controls
316 lines (282 loc) · 14.9 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Share & Rate</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #0d1117;
color: #c9d1d9;
}
</style>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
import { getFirestore, doc, getDoc, addDoc, setDoc, updateDoc, onSnapshot, collection, query, serverTimestamp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";
// Firebase global variables provided by the canvas environment
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};
const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null;
// Gemini API configuration
const API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent?key=';
const apiKey = ''; // Provided by the environment
// --- Firebase Initialization ---
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
let userId = null;
// UI elements
const imageGrid = document.getElementById('imageGrid');
const shareForm = document.getElementById('shareForm');
const imageUrlInput = document.getElementById('imageUrlInput');
const messageContainer = document.getElementById('message');
const userIdDisplay = document.getElementById('userIdDisplay');
const loadingIndicator = document.getElementById('loadingIndicator');
const generateForm = document.getElementById('generateForm');
const promptInput = document.getElementById('promptInput');
const generateBtn = document.getElementById('generateBtn');
// --- Utility Functions ---
function showMessage(msg, type = 'info') {
messageContainer.textContent = msg;
messageContainer.className = `p-3 rounded-xl mt-4 text-center ${
type === 'error' ? 'bg-red-500 text-white' : 'bg-blue-500 text-white'
}`;
}
// --- Firebase Authentication ---
onAuthStateChanged(auth, async (user) => {
if (user) {
userId = user.uid;
userIdDisplay.textContent = `Your ID: ${userId}`;
loadingIndicator.style.display = 'none';
document.getElementById('mainContent').classList.remove('hidden');
setupRealtimeListener();
} else {
try {
if (initialAuthToken) {
await signInWithCustomToken(auth, initialAuthToken);
} else {
await signInAnonymously(auth);
}
} catch (error) {
console.error("Authentication Error:", error);
showMessage('Failed to authenticate. Please try again.', 'error');
}
}
});
// --- Firestore Real-time Listener ---
function setupRealtimeListener() {
const imagesCollection = collection(db, `artifacts/${appId}/public/data/images`);
onSnapshot(imagesCollection, (snapshot) => {
imageGrid.innerHTML = ''; // Clear existing images
const images = [];
snapshot.forEach((doc) => {
images.push({ id: doc.id, ...doc.data() });
});
// Sort images by creation time, newest first
images.sort((a, b) => (b.createdAt?.toMillis() || 0) - (a.createdAt?.toMillis() || 0));
if (images.length === 0) {
imageGrid.innerHTML = '<p class="text-center text-gray-400 col-span-1 md:col-span-3">No images shared yet. Be the first!</p>';
} else {
images.forEach(renderImageCard);
}
}, (error) => {
console.error("Firestore error:", error);
showMessage('Failed to load images. Check your internet connection.', 'error');
});
}
// --- UI Rendering ---
function renderImageCard(image) {
const card = document.createElement('div');
card.className = 'bg-gray-800 rounded-xl shadow-lg overflow-hidden flex flex-col transform transition-transform hover:scale-105 duration-200';
// Calculate average rating
const ratingsMap = image.ratings || {};
const ratingsCount = Object.keys(ratingsMap).length;
const totalRating = Object.values(ratingsMap).reduce((sum, rating) => sum + rating, 0);
const averageRating = ratingsCount > 0 ? (totalRating / ratingsCount).toFixed(1) : 'N/A';
const userRating = ratingsMap[userId] || 0;
const isAI = image.type === 'ai';
const imageSource = isAI ? `data:image/png;base64,${image.url}` : image.url;
const aiLabel = isAI ? `<div class="absolute top-2 left-2 bg-blue-500 text-white text-xs px-2 py-1 rounded-full">AI-Generated</div>` : '';
card.innerHTML = `
<div class="relative w-full h-48 sm:h-64">
<img src="${imageSource}" alt="Shared Image" class="w-full h-full object-cover">
${aiLabel}
<div class="absolute top-2 right-2 bg-black bg-opacity-75 text-white text-xs px-2 py-1 rounded-full">
⭐ ${averageRating} (${ratingsCount} votes)
</div>
</div>
<div class="p-4 flex flex-col justify-between flex-grow">
<div class="mb-4">
<p class="text-sm text-gray-400 truncate">Shared by: ${image.sharedBy.length > 8 ? `${image.sharedBy.substring(0, 8)}...` : image.sharedBy}</p>
${isAI ? `<p class="text-xs text-gray-500 mt-1 italic">Prompt: "${image.prompt}"</p>` : ''}
</div>
<div class="flex items-center justify-center space-x-1 rating-stars text-2xl" data-id="${image.id}">
${[1, 2, 3, 4, 5].map(star => `
<i class="fa-solid fa-star cursor-pointer transition-colors duration-200 ${userRating >= star ? 'text-yellow-400' : 'text-gray-600 hover:text-yellow-300'}" data-rating="${star}"></i>
`).join('')}
</div>
</div>
`;
imageGrid.appendChild(card);
}
// --- Gemini API Call ---
async function generateAndShareImage(prompt) {
const url = `${API_URL}${apiKey}`;
const payload = {
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
responseModalities: ["IMAGE"],
},
};
generateBtn.disabled = true;
generateBtn.innerHTML = `
<div class="inline-block h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent text-white mr-2"></div>
Generating...
`;
showMessage('Generating image with AI...', 'info');
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
const result = await response.json();
const base64Data = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
if (base64Data) {
await addDoc(collection(db, `artifacts/${appId}/public/data/images`), {
url: base64Data,
prompt: prompt,
sharedBy: userId,
createdAt: serverTimestamp(),
ratings: {},
type: 'ai'
});
promptInput.value = '';
showMessage('AI image shared successfully!', 'info');
} else {
showMessage('Failed to generate image. Please try a different prompt.', 'error');
}
} catch (error) {
console.error("Gemini API Error:", error);
showMessage('Failed to generate image. Please check your prompt or network.', 'error');
} finally {
generateBtn.disabled = false;
generateBtn.innerHTML = '✨ Generate & Share Image';
}
}
// --- Event Listeners ---
shareForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (!userId) {
showMessage('Please wait, authenticating user...', 'info');
return;
}
const imageUrl = imageUrlInput.value.trim();
if (!imageUrl) {
showMessage('Please enter an image URL.', 'error');
return;
}
showMessage('Sharing image...', 'info');
try {
await addDoc(collection(db, `artifacts/${appId}/public/data/images`), {
url: imageUrl,
sharedBy: userId,
createdAt: serverTimestamp(),
ratings: {},
type: 'url'
});
imageUrlInput.value = '';
showMessage('Image shared successfully!');
} catch (error) {
console.error("Error adding document:", error);
showMessage('Failed to share image. Please try again.', 'error');
}
});
generateForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (!userId) {
showMessage('Please wait, authenticating user...', 'info');
return;
}
const prompt = promptInput.value.trim();
if (!prompt) {
showMessage('Please enter a prompt for the AI.', 'error');
return;
}
await generateAndShareImage(prompt);
});
imageGrid.addEventListener('click', async (e) => {
if (!userId) {
showMessage('Please wait, authenticating user...', 'info');
return;
}
const star = e.target.closest('.fa-star');
if (!star) return;
const rating = parseInt(star.dataset.rating, 10);
const imageCard = star.closest('.rating-stars');
const imageId = imageCard.dataset.id;
try {
const imageRef = doc(db, `artifacts/${appId}/public/data/images`, imageId);
const docSnap = await getDoc(imageRef);
if (docSnap.exists()) {
const currentRatings = docSnap.data().ratings || {};
const newRatings = { ...currentRatings, [userId]: rating };
await updateDoc(imageRef, { ratings: newRatings });
}
} catch (error) {
console.error("Error rating image:", error);
showMessage('Failed to submit rating. Please try again.', 'error');
}
});
</script>
</head>
<body class="p-4 sm:p-8">
<div class="container mx-auto max-w-5xl bg-gray-900 rounded-3xl shadow-2xl p-6 sm:p-12">
<header class="text-center mb-10">
<h1 class="text-4xl sm:text-5xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-500 mb-2">
Share & Rate
</h1>
<p class="text-gray-400 text-lg sm:text-xl">
Share images with friends and see what they think.
</p>
</header>
<div id="loadingIndicator" class="text-center p-8">
<div class="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-r-transparent text-blue-400"></div>
<p class="mt-2 text-gray-400">Loading...</p>
</div>
<div id="mainContent" class="hidden">
<div class="text-center mb-6">
<p id="userIdDisplay" class="text-sm text-gray-500 p-2 bg-gray-800 rounded-xl inline-block font-mono break-all"></p>
</div>
<div class="flex flex-col sm:flex-row gap-4 mb-8">
<form id="shareForm" class="flex flex-col sm:flex-row gap-4 w-full">
<input type="url" id="imageUrlInput" placeholder="Paste image URL here" required class="flex-grow p-4 bg-gray-800 border border-gray-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 text-white placeholder-gray-500">
<button type="submit" class="bg-gradient-to-r from-blue-500 to-purple-600 text-white font-bold py-4 px-8 rounded-xl shadow-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-300">
Share
</button>
</form>
</div>
<div class="flex flex-col sm:flex-row gap-4 mb-8">
<form id="generateForm" class="flex flex-col sm:flex-row gap-4 w-full">
<input type="text" id="promptInput" placeholder="Enter a prompt to generate an image..." required class="flex-grow p-4 bg-gray-800 border border-gray-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-purple-500 text-white placeholder-gray-500">
<button type="submit" id="generateBtn" class="bg-gradient-to-r from-purple-500 to-pink-600 text-white font-bold py-4 px-8 rounded-xl shadow-lg hover:from-purple-600 hover:to-pink-700 transition-all duration-300">
✨ Generate & Share Image
</button>
</form>
</div>
<div id="message" class="text-center"></div>
<div id="imageGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mt-8">
<!-- Image cards will be rendered here by JavaScript -->
</div>
</div>
</div>
</body>
</html>