-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
506 lines (444 loc) · 20.1 KB
/
script.js
File metadata and controls
506 lines (444 loc) · 20.1 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const ingredientTab = document.getElementById('ingredient-tab');
const nameTab = document.getElementById('name-tab');
const ingredientPanel = document.getElementById('ingredient-panel');
const namePanel = document.getElementById('name-panel');
const ingredientInput = document.getElementById('ingredient-input');
const addIngredientBtn = document.getElementById('add-ingredient');
const ingredientTags = document.getElementById('ingredient-tags');
const generateRecipeBtn = document.getElementById('generate-recipe');
const recipeNameInput = document.getElementById('recipe-name-input');
const searchRecipeBtn = document.getElementById('search-recipe');
const resultsSection = document.getElementById('results-section');
const recipeGrid = document.getElementById('recipe-grid');
const loading = document.getElementById('loading');
const recipeModal = document.getElementById('recipe-modal');
const closeModal = document.getElementById('close-modal');
const modalRecipeTitle = document.getElementById('modal-recipe-title');
const modalRecipeTime = document.getElementById('modal-recipe-time');
const modalRecipeDiet = document.getElementById('modal-recipe-diet');
const modalRecipeCuisine = document.getElementById('modal-recipe-cuisine');
const modalIngredientsList = document.getElementById('modal-ingredients-list');
const modalInstructionsList = document.getElementById('modal-instructions-list');
const saveRecipeBtn = document.getElementById('save-recipe');
const dietFilter = document.getElementById('diet-filter');
const cuisineFilter = document.getElementById('cuisine-filter');
const timeFilter = document.getElementById('time-filter');
const toggleEnglish = document.getElementById('toggle-language');
const toggleBengali = document.getElementById('toggle-bengali');
// API Keys
const SPOONACULAR_API_KEY = 'your_api_key';
const OPENAI_API_KEY = 'Your_api-key';
// State
let selectedIngredients = [];
let currentRecipes = [];
let currentRecipeDetails = null;
let currentLanguage = 'en'; // 'en' or 'bn'
let originalRecipeDetails = null;
// Initialize the app
function init() {
setupEventListeners();
}
function setupEventListeners() {
// Tab Switching
ingredientTab.addEventListener('click', () => switchTab('ingredient'));
nameTab.addEventListener('click', () => switchTab('name'));
// Language Toggle
toggleEnglish.addEventListener('click', () => switchLanguage('en'));
toggleBengali.addEventListener('click', () => switchLanguage('bn'));
// Ingredient Management
addIngredientBtn.addEventListener('click', addIngredient);
ingredientInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') addIngredient();
});
// Recipe Actions
generateRecipeBtn.addEventListener('click', generateRecipesByIngredients);
searchRecipeBtn.addEventListener('click', () => {
const recipeName = recipeNameInput.value.trim();
if (recipeName) searchRecipesByName(recipeName);
});
recipeNameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && recipeNameInput.value.trim()) {
searchRecipesByName(recipeNameInput.value.trim());
}
});
// Modal Actions
closeModal.addEventListener('click', closeRecipeModal);
window.addEventListener('click', (event) => {
if (event.target === recipeModal) closeRecipeModal();
});
saveRecipeBtn.addEventListener('click', saveCurrentRecipe);
}
function switchTab(tab) {
if (tab === 'ingredient') {
ingredientTab.classList.add('active');
nameTab.classList.remove('active');
ingredientPanel.classList.add('active');
namePanel.classList.remove('active');
} else {
nameTab.classList.add('active');
ingredientTab.classList.remove('active');
namePanel.classList.add('active');
ingredientPanel.classList.remove('active');
}
}
function switchLanguage(lang) {
currentLanguage = lang;
toggleEnglish.classList.toggle('active', lang === 'en');
toggleBengali.classList.toggle('active', lang === 'bn');
if (currentRecipeDetails) {
if (lang === 'bn') {
showLoading();
translateRecipeToBengali(originalRecipeDetails)
.then(translated => {
displayRecipeDetails(translated);
hideLoading();
})
.catch(error => {
console.error('Translation error:', error);
displayRecipeDetails(originalRecipeDetails);
hideLoading();
});
} else {
displayRecipeDetails(originalRecipeDetails);
}
}
}
function addIngredient() {
const ingredient = ingredientInput.value.trim().toLowerCase();
if (ingredient && !selectedIngredients.includes(ingredient)) {
selectedIngredients.push(ingredient);
renderIngredientTags();
ingredientInput.value = '';
}
}
function renderIngredientTags() {
ingredientTags.innerHTML = '';
selectedIngredients.forEach(ingredient => {
const tag = document.createElement('div');
tag.className = 'ingredient-tag';
tag.innerHTML = `
${ingredient}
<button class="remove-ingredient" data-ingredient="${ingredient}">
<i class="fas fa-times"></i>
</button>
`;
ingredientTags.appendChild(tag);
});
document.querySelectorAll('.remove-ingredient').forEach(btn => {
btn.addEventListener('click', function() {
selectedIngredients = selectedIngredients.filter(
i => i !== this.getAttribute('data-ingredient')
);
renderIngredientTags();
});
});
}
async function generateRecipesByIngredients() {
if (selectedIngredients.length === 0) {
alert('Please add at least one ingredient');
return;
}
showLoading();
const diet = dietFilter.value;
const cuisine = cuisineFilter.value;
const maxReadyTime = timeFilter.value;
try {
// Try Spoonacular API first
let recipes = await fetchRecipesFromSpoonacular(selectedIngredients, diet, cuisine, maxReadyTime);
if (!recipes || recipes.length === 0) {
// Fallback to AI if Spoonacular fails
recipes = await generateRecipesWithAI(selectedIngredients, diet, cuisine, maxReadyTime);
}
currentRecipes = recipes;
displayRecipes(recipes);
} catch (error) {
console.error('Error:', error);
alert('Failed to fetch recipes. Please try again.');
} finally {
hideLoading();
}
}
async function searchRecipesByName(query) {
showLoading();
try {
// Try Spoonacular API first
let recipes = await searchRecipesFromSpoonacular(query);
if (!recipes || recipes.length === 0) {
// Fallback to AI if Spoonacular fails
recipes = await searchRecipesWithAI(query);
}
currentRecipes = recipes;
displayRecipes(recipes);
} catch (error) {
console.error('Error:', error);
alert('Failed to search recipes. Please try again.');
} finally {
hideLoading();
}
}
// Spoonacular API Functions
async function fetchRecipesFromSpoonacular(ingredients, diet, cuisine, maxReadyTime) {
const ingredientsStr = ingredients.join(',+');
let url = `https://api.spoonacular.com/recipes/findByIngredients?ingredients=${ingredientsStr}&number=6&apiKey=${SPOONACULAR_API_KEY}`;
if (diet) url += `&diet=${diet}`;
if (cuisine) url += `&cuisine=${cuisine}`;
if (maxReadyTime) url += `&maxReadyTime=${maxReadyTime}`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error('API error');
const data = await response.json();
return data.map(recipe => ({
id: recipe.id,
title: recipe.title,
image: recipe.image,
usedIngredients: recipe.usedIngredients,
missedIngredients: recipe.missedIngredients,
likes: recipe.likes
}));
} catch (error) {
console.error('Spoonacular error:', error);
return null;
}
}
async function searchRecipesFromSpoonacular(query) {
const url = `https://api.spoonacular.com/recipes/complexSearch?query=${encodeURIComponent(query)}&number=6&apiKey=${SPOONACULAR_API_KEY}`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error('API error');
const data = await response.json();
return data.results.map(recipe => ({
id: recipe.id,
title: recipe.title,
image: recipe.image
}));
} catch (error) {
console.error('Spoonacular error:', error);
return null;
}
}
async function getRecipeDetailsFromSpoonacular(id) {
const url = `https://api.spoonacular.com/recipes/${id}/information?includeNutrition=false&apiKey=${SPOONACULAR_API_KEY}`;
try {
const response = await fetch(url);
if (!response.ok) throw new Error('API error');
const data = await response.json();
return {
title: data.title,
image: data.image,
readyInMinutes: data.readyInMinutes,
servings: data.servings,
ingredients: data.extendedIngredients.map(ing => ing.original),
instructions: data.instructions ? data.instructions.replace(/<[^>]*>/g, '') : 'No instructions provided',
diets: data.diets || [],
cuisines: data.cuisines || []
};
} catch (error) {
console.error('Error:', error);
return null;
}
}
// AI Functions
async function generateRecipesWithAI(ingredients, diet, cuisine, maxReadyTime) {
const prompt = `Generate 3 recipes using: ${ingredients.join(', ')}.
${diet ? `Diet: ${diet}. ` : ''}
${cuisine ? `Cuisine: ${cuisine}. ` : ''}
${maxReadyTime ? `Max time: ${maxReadyTime} mins. ` : ''}
Provide title, ingredients array, and instructions (steps separated by newlines).
Return as JSON array with title, ingredients, instructions.`;
try {
const recipes = await callOpenAI(prompt, false);
return recipes.map((recipe, index) => ({
id: `ai-${index}`,
title: recipe.title,
ingredients: recipe.ingredients,
instructions: recipe.instructions,
isAI: true
}));
} catch (error) {
console.error('AI error:', error);
throw error;
}
}
async function searchRecipesWithAI(query) {
const prompt = `Generate 3 recipes based on: "${query}".
Provide title, ingredients array, and instructions (steps separated by newlines).
Return as JSON array with title, ingredients, instructions.`;
try {
const recipes = await callOpenAI(prompt, false);
return recipes.map((recipe, index) => ({
id: `ai-${index}`,
title: recipe.title,
ingredients: recipe.ingredients,
instructions: recipe.instructions,
isAI: true
}));
} catch (error) {
console.error('AI error:', error);
throw error;
}
}
async function translateRecipeToBengali(recipe) {
const prompt = `Translate to Bengali (বাংলা):
Title: ${recipe.title}
Ingredients: ${recipe.ingredients.join('; ')}
Instructions: ${recipe.instructions}
Keep measurements in English.
Return as JSON with title, ingredients array, instructions.`;
try {
const translated = await callOpenAI(prompt, true);
return {
...recipe,
title: translated.title || recipe.title,
ingredients: translated.ingredients || recipe.ingredients,
instructions: translated.instructions || recipe.instructions
};
} catch (error) {
console.error('Translation error:', error);
return recipe;
}
}
async function callOpenAI(prompt, isTranslation) {
const url = 'https://api.openai.com/v1/chat/completions';
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: isTranslation ?
'You translate recipes to Bengali. Keep measurements in English.' :
'You generate recipes in JSON format.'
},
{
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 1500
})
});
if (!response.ok) throw new Error('API error');
const data = await response.json();
const content = data.choices[0]?.message?.content;
return JSON.parse(content);
} catch (error) {
console.error('OpenAI error:', error);
throw error;
}
}
// Display Functions
function displayRecipes(recipes) {
recipeGrid.innerHTML = '';
if (!recipes || recipes.length === 0) {
recipeGrid.innerHTML = '<p class="no-results">No recipes found. Try different search terms.</p>';
resultsSection.style.display = 'block';
return;
}
recipes.forEach(recipe => {
const recipeCard = document.createElement('div');
recipeCard.className = 'recipe-card';
const imageUrl = recipe.image || `https://source.unsplash.com/random/300x200/?food,${encodeURIComponent(recipe.title)}`;
recipeCard.innerHTML = `
<div class="recipe-img" style="background-image: url('${imageUrl}')"></div>
<div class="recipe-info">
<h3 class="recipe-title">${recipe.title}</h3>
<div class="recipe-meta">
${recipe.readyInMinutes ? `<span><i class="far fa-clock"></i> ${recipe.readyInMinutes} min</span>` : ''}
${recipe.likes ? `<span><i class="far fa-thumbs-up"></i> ${recipe.likes}</span>` : ''}
</div>
<p class="recipe-description">
${recipe.missedIngredients ? `Uses ${recipe.usedIngredients?.length || 0} ingredients you have` : ''}
</p>
<button class="view-recipe" data-id="${recipe.id}" data-is-ai="${recipe.isAI || false}">View Recipe</button>
</div>
`;
recipeCard.querySelector('.view-recipe').addEventListener('click', async () => {
showLoading();
try {
const recipeId = recipe.id;
const isAI = recipe.isAI || false;
if (isAI) {
originalRecipeDetails = {
title: recipe.title,
ingredients: recipe.ingredients,
instructions: recipe.instructions,
isAI: true
};
currentRecipeDetails = originalRecipeDetails;
} else {
const details = await getRecipeDetailsFromSpoonacular(recipeId);
if (details) {
originalRecipeDetails = details;
currentRecipeDetails = details;
}
}
if (currentLanguage === 'bn' && currentRecipeDetails) {
const translated = await translateRecipeToBengali(currentRecipeDetails);
displayRecipeDetails(translated);
} else if (currentRecipeDetails) {
displayRecipeDetails(currentRecipeDetails);
}
} catch (error) {
console.error('Error:', error);
alert('Failed to load recipe details');
} finally {
hideLoading();
}
});
recipeGrid.appendChild(recipeCard);
});
resultsSection.style.display = 'block';
}
function displayRecipeDetails(recipe) {
modalRecipeTitle.textContent = recipe.title;
modalRecipeTime.innerHTML = recipe.readyInMinutes ?
`<i class="far fa-clock"></i> ${recipe.readyInMinutes} min` : '';
modalRecipeDiet.innerHTML = recipe.diets?.length > 0 ?
`<i class="fas fa-utensils"></i> ${recipe.diets.join(', ')}` : '';
modalRecipeCuisine.innerHTML = recipe.cuisines?.length > 0 ?
`<i class="fas fa-globe-americas"></i> ${recipe.cuisines.join(', ')}` : '';
modalIngredientsList.innerHTML = '';
(recipe.ingredients || []).forEach(ingredient => {
const li = document.createElement('li');
li.textContent = ingredient;
modalIngredientsList.appendChild(li);
});
modalInstructionsList.innerHTML = '';
const instructions = recipe.instructions || 'No instructions provided.';
const steps = instructions.split(/\n|\d+\./).filter(step => step.trim());
steps.forEach(step => {
const li = document.createElement('li');
li.textContent = step.trim();
modalInstructionsList.appendChild(li);
});
recipeModal.style.display = 'block';
document.body.style.overflow = 'hidden';
}
function closeRecipeModal() {
recipeModal.style.display = 'none';
document.body.style.overflow = 'auto';
}
function saveCurrentRecipe() {
if (currentRecipeDetails) {
alert(`Recipe "${currentRecipeDetails.title}" saved!`);
}
}
function showLoading() {
loading.style.display = 'flex';
resultsSection.style.display = 'none';
}
function hideLoading() {
loading.style.display = 'none';
}
// Initialize the app
init();
});