sustainability_scorer / sustanability_scorer.py
yizypizy's picture
initial commit
5e79820
import os
from openai import OpenAI
import base64
from pydantic import BaseModel
from PIL import Image
import io
import json
import random
class HouseFeature(BaseModel):
age_in_years: int
solar_panel: bool
green_roof: bool
is_property: bool
IMAGE_PATH = "house7.png"
# Open the image file and encode it as a base64 string
def encode_image(image, output_format="JPEG"):
# Resize the image
image = image.resize((256, 256))
# Convert the image to bytes
buffered = io.BytesIO()
# Save the image in the specified format
image.save(buffered, format=output_format)
image_bytes = buffered.getvalue()
# Encode the image bytes to base64
base64_encoded_data = base64.b64encode(image_bytes)
# Convert bytes to string
base64_encoded_string = base64_encoded_data.decode("utf-8")
return base64_encoded_string
def openai_completion(base64_image):
# Initialize OpenAI API key from environment variable
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
MODEL = "gpt-4o-mini"
response = client.beta.chat.completions.parse(
model=MODEL,
messages=[
{
"role": "system",
"content": "You are a house expert who can estimate house's age. Help me identify houses!",
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "Estimate the house's age and whether it has solar panels.",
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
},
],
max_tokens=300,
response_format=HouseFeature,
)
return response.choices[0].message.content
def sustainability_scorer(house_features: HouseFeature):
# Calculate sustainability score based on house features, best score 100, lowest 30
score = 0
if house_features.is_property:
if house_features.age_in_years < 10:
score += 70
elif house_features.age_in_years < 20:
score += 65
elif house_features.age_in_years < 30:
score += 45
else:
score += 25
if house_features.solar_panel:
score += 40
if house_features.green_roof:
score += 30
score += random.randint(0, 5)
# score can't be over 100
score = min(score, 100)
if score > 80:
color = "green"
feedback = "🌟 Excellent! 🌟"
elif score > 50:
color = "orange"
feedback = "πŸ‘ Good!"
else:
color = "red"
feedback = "❗️ Needs Improvement"
return f"<div class='score_output' style='color: {color};'>{feedback}<br>Sustainability Score: {score}</div>"
else:
return "Sorry, I'm unable to identify your house from the picture"