Skip to content

Commit

Permalink
Get links working with imgur
Browse files Browse the repository at this point in the history
  • Loading branch information
caseyavila committed Dec 7, 2023
1 parent 0ba6bb2 commit 87ea070
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 73 deletions.
49 changes: 15 additions & 34 deletions Backend/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,14 @@
import requests
from flask_cors import CORS, cross_origin

from mongoengine import (
connect,
Document,
StringField,
BinaryField,
DoesNotExist,
)
from werkzeug.security import generate_password_hash, check_password_hash
import secrets # For generating a session key

from datetime import datetime

import db_access
from db_access import User
from db_access import Image
from db_access import (
check_user,
create_user,
db_connect,
# get_image,
create_image,
)

import base64

Expand All @@ -42,11 +29,6 @@
app.config["JWT_SECRET_KEY"] = "CHANGE_TO_SECURE_KEY"
jwt = JWTManager(app)

DB_ACCESS_URL = ( # This is where db_access.py is running.
"http://127.0.0.1:5001"
)


@app.route("/generate_image", methods=["POST"])
@jwt_required()
def generate_image():
Expand Down Expand Up @@ -107,17 +89,19 @@ def store_image():
if field not in data:
return jsonify({"error": f"Missing field: {field}"}), 400

image_res = requests.get(data["url"])
image_res = requests.post("https://api.imgur.com/3/image",
data={"image": data["url"]},
headers={"Authorization": "Client-ID " + os.environ["IMGUR_CLIENT_ID"]})

# Prepare the data for creating an image
image_data = {
"creator": current_user, # Assuming the creator is the logged-in user
"prompt": data["prompt"],
"data": image_res.content,
"url": image_res.json()["data"]["link"]
}

# Call the create_image function from db_access
response = create_image(image_data)
response = db_access.create_image(image_data)

# Handle the response
if response.status_code == 201:
Expand All @@ -139,15 +123,12 @@ def fetch_portfolio():
portfolio_images = User.objects.get(pk=user).portfolio

# Format the response with the list of images
portfolio = [
{
"image_id": str(image.id),
"prompt": image.prompt,
"creator": user,
"data": base64.b64encode(image.data).decode("ascii"),
}
for image in portfolio_images
]
portfolio = [{
"image_id": str(image.id),
"prompt": image.prompt,
"creator": user,
"url": image.url
} for image in portfolio_images]

return jsonify(portfolio), 200

Expand Down Expand Up @@ -259,15 +240,15 @@ def register():
"password": hashed_password,
"portfolio": portfolio,
}
response = check_user(user_data)
response = db_acess.check_user(user_data)
if response.status_code == 401:
print(f"responsey={response.message}")
return (
jsonify({"message": response.message}),
400,
)
# Send the user data with the hashed password to the database access layer
response = create_user(user_data)
response = db_access.create_user(user_data)
# Handle the response from the database access layer
if response.status_code == 201:
print("User created successfully!")
Expand Down Expand Up @@ -300,7 +281,7 @@ def verify_user():
return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
db_connect()
db_access.db_connect()
try:
app.run(port=5000, debug=True)
except OSError as e:
Expand Down
28 changes: 3 additions & 25 deletions Backend/db_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ class User(Document):
class Image(Document):
creator = ReferenceField(User, required=True)
prompt = StringField(required=True)
data = BinaryField(required=True)
elo = IntField(required=True)
url = StringField(required=True)
elo = IntField(required=False)

meta = {"collection": "images"}

Expand Down Expand Up @@ -111,7 +111,7 @@ def create_image(data):
image = Image(
creator=data["creator"],
prompt=data["prompt"],
data=data["data"]
url=data["url"]
)
image.save()

Expand All @@ -125,25 +125,3 @@ def create_image(data):
return Response("Creator user does not exist.", 404,{})
except Exception as e:
return Response(f"Internal server error: {e}", 500,{})


# FUNCTION EXISTS IN db_access
# def get_portfolio(username):
# try:
# user = User.objects.get(username=username)
# portfolio_images = User.objects.get(pk=user).portfolio
# images = Image.objects(creator=user)


# return jsonify(
# portfolio_images
# # {
# # "image_id": str(image.id),
# # "prompt": image.prompt,
# # "url": image.url,
# # } for image in images
# ), 200
# except DoesNotExist:
# return Response("User not found.", 404,{})
# except Exception as e:
# return Response(f"Internal server error {e}", 500,{})
5 changes: 4 additions & 1 deletion Frontend/src/pages/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default function Create() {
try {
setGenerating(true);
setFailed(false);
setImageAccepted(null);
await axios.post(
"http://localhost:5000/generate_image",
{ prompt: text },
Expand All @@ -37,6 +38,8 @@ export default function Create() {
}).then(() => setGenerating(false));

} catch (error) {
setFailed(true);
setGenerating(false);
console.error("Error:", error);
}
};
Expand Down Expand Up @@ -141,4 +144,4 @@ export async function getServerSideProps(context) {
return {
props: {}, // Will be passed to the page component as props
};
}
}
22 changes: 9 additions & 13 deletions Frontend/src/pages/portfolio.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,15 @@ export default function Portfolio() {
}, []);

return (
<div className="p-6">
<div className="bg-gray-100 min-h-screen p-6">
<h1 className="text-2xl mb-4">Portfolio</h1>
<div className="grid grid-cols-3 gap-4">
{portfolio &&
portfolio.map((image) => (
<Image
src={"data:image/png;base64, " + image.data}
loader={() => image.url}
height={500}
width={500}
alt="Portfolio Image"
/>
))}
<div className="grid grid-cols-5 gap-4 content-stretch">
{portfolio && portfolio.map((image) =>
<Image src={image.url}
loader={() => image.url}
height={1024}
width={1024}
/>)}
</div>
</div>
);
Expand All @@ -61,4 +57,4 @@ export async function getServerSideProps(context) {
return {
props: {}, // Will be passed to the page component as props
};
}
}

0 comments on commit 87ea070

Please sign in to comment.