Skip to content

Commit

Permalink
Merge pull request #50 from vxshxk/save-dish-pics
Browse files Browse the repository at this point in the history
Save dish pics
  • Loading branch information
yukitya-1811 authored Jun 23, 2024
2 parents f917e0b + b4c0d12 commit 4e0d82c
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 38 deletions.
4 changes: 3 additions & 1 deletion recipify/recipify/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.contrib import admin
from .models import FoodImage
from .models import Recipe
from .models import DishImage

admin.site.register(FoodImage)
admin.site.register(Recipe)
admin.site.register(Recipe)
admin.site.register(DishImage)
22 changes: 22 additions & 0 deletions recipify/recipify/migrations/0006_dishimage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 4.2.11 on 2024-06-22 20:59

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('recipify', '0005_recipe_image'),
]

operations = [
migrations.CreateModel(
name='DishImage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(upload_to='images/')),
('recipe', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='recipify.recipe')),
],
),
]
18 changes: 18 additions & 0 deletions recipify/recipify/migrations/0007_alter_dishimage_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.11 on 2024-06-23 11:32

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('recipify', '0006_dishimage'),
]

operations = [
migrations.AlterField(
model_name='dishimage',
name='image',
field=models.URLField(),
),
]
4 changes: 4 additions & 0 deletions recipify/recipify/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ class Recipe(models.Model):
nutrients_present = models.TextField(null=True)
nutrients_absent = models.TextField(null=True)
image = models.ForeignKey(FoodImage, null=True, on_delete=models.CASCADE)

class DishImage(models.Model):
image = models.URLField()
recipe = models.OneToOneField(Recipe, null=True, on_delete=models.CASCADE)
4 changes: 3 additions & 1 deletion recipify/recipify/templates/show.html
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ <h1 class="mb-4 text-3xl font-extrabold text-gray-900 dark:text-white md:text-5x
</ul>
</div>
<div class="recipe-img">
<img style="border-radius: 15px;" src="{{ foodimg }}" alt="food image"/>
<a href="{{ foodimg.image }}">
<img style="border-radius: 15px; height: 100%; width: 100%; object-fit: cover;" src="{{ foodimg.image }}" alt="food image"/>
</a>
</div>
</div>
</div>
Expand Down
63 changes: 35 additions & 28 deletions recipify/recipify/util_functions/image_generation.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,45 @@
import requests
import json
from PIL import Image
import base64
from io import BytesIO

# def add_base64_padding(base64_string):
# missing_padding = len(base64_string) % 4
# if missing_padding:
# base64_string += '=' * (4 - missing_padding)
# return base64_string

def add_base64_padding(base64_string):
missing_padding = len(base64_string) % 4
if missing_padding:
base64_string += '=' * (4 - missing_padding)
return base64_string

def decode_base64_to_image(base64_string):
base64_string = add_base64_padding(base64_string)
image_data = base64.b64decode(base64_string)
image = Image.open(BytesIO(image_data))
return image
# def decode_base64_to_image(base64_string):
# base64_string = add_base64_padding(base64_string)
# image_data = base64.b64decode(base64_string)
# image = Image.open(BytesIO(image_data))
# return image

def getDishImage(dishname):
url = "https://api.serphouse.com/serp/live?q=" + dishname + " image&engine=google_images&lang=en&device=desktop&serp_type=web&loc=Alba,Texas,United States&loc_id=1026201&verbatim=0&gfilter=0&page=1&num_result=10"
client_ID = "94XalRwyaaUtAh8AuRoE_gp3QmvntuuFI_otx2Wsvso"
url = "https://api.unsplash.com/search/photos/?client_id=" + client_ID + "&query=" + dishname


payload = {}
headers = {
'Authorization': 'Bearer nddeuNFHxu2hxN0wzW8euCXbUOawG25WLnpNFdiggt8q4wPKiWTx8AS9T1Iw'
}
try:
response = requests.request("GET", url)
response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
ans = json.loads(response.text)
image_url = ans['results'][0]['urls']['regular']
return image_url
except requests.exceptions.RequestException as e:
# Handle any requests exceptions (e.g., network issues, invalid responses)
print(f"An error occurred with the request: {e}")
except json.JSONDecodeError as e:
# Handle JSON decoding errors
print(f"An error occurred while decoding the JSON response: {e}")
except (KeyError, IndexError) as e:
# Handle errors related to accessing specific elements in the JSON response
print(f"An error occurred while accessing the JSON data: {e}")
except Exception as e:
# Handle any other unforeseen exceptions
print(f"An unexpected error occurred: {e}")

response = requests.request("GET", url, headers=headers, data=payload)
ans = json.loads(response.text)
image_base_64 = ans['results']['results']['inline_images'][0]['image']
return image_base_64
return None

# Example usage
# dish_image_base64 = getDishImage("Kiwi Salsa")
# print(dish_image_base64)
# image = decode_base64_to_image(dish_image_base64)
# image.show()
# Test
# img = getDishImage("Kiwi Grill ")
# print(img)

20 changes: 16 additions & 4 deletions recipify/recipify/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .forms import SignupForm, LoginForm
from .models import FoodImage
from .models import Recipe
from .models import DishImage
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from inference_sdk import InferenceHTTPClient
Expand Down Expand Up @@ -108,8 +109,18 @@ def image_upload_view(request):
nutrients_absent=nutrients_absent[i],
image=food_image,
)

recipes.append(recipe)
recipe.save()
dish_img = getDishImage(dishNames[i])

if dish_img: # Ensure dish_img is not None or empty
dimg = DishImage(image=dish_img, recipe=recipe)
dimg.save()
else:
dimg = DishImage(image="https://static.vecteezy.com/system/resources/previews/000/542/269/original/healthy-food-vector.jpg", recipe=recipe)
dimg.save()


# Load parsed text into context dictionary to display on page
context = {
Expand All @@ -136,10 +147,11 @@ def show_recipe(request, id):
nutri_present = [clean(nutri) for nutri in nutri_present]
nutri_absent = recipe.nutrients_absent.split("',")
nutri_absent = [clean(nutri) for nutri in nutri_absent]
try:
img = getDishImage(recipeName)
except:
img = recipe.image
img = get_object_or_404(DishImage, recipe=recipe)
# try:
# img = getDishImage(recipeName)
# except:
# img = recipe.image

context = {
"ingredients": ingredients,
Expand Down
6 changes: 2 additions & 4 deletions recipify/static/css/show.css
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ body {
}

.recipe-img {
max-height: 100%;
max-width: 100%;
height: auto;
width: auto;
height: 400px;
width: 400px;

}
Binary file added recipify/static/img/default.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 4e0d82c

Please sign in to comment.