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
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import google.generativeai as genai
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
from google.colab import files
|
| 10 |
+
|
| 11 |
+
# Set up the Generative AI API key
|
| 12 |
+
api_key = os.getenv('GOOGLE_API_KEY') # Use environment variable for API key security
|
| 13 |
+
genai.configure(api_key=api_key)
|
| 14 |
+
|
| 15 |
+
categories = ["Personal Care", "Household Care", "Dairy", "Staples", "Snacks and Beverages", "Packaged Food", "Fruits and Vegetables"]
|
| 16 |
+
|
| 17 |
+
# Step 1: Download image from URL
|
| 18 |
+
def download_image(image_url):
|
| 19 |
+
try:
|
| 20 |
+
response = requests.get(image_url)
|
| 21 |
+
response.raise_for_status() # Check if the request was successful
|
| 22 |
+
img = Image.open(BytesIO(response.content))
|
| 23 |
+
temp_path = "temp_image.jpg" # Temporary path
|
| 24 |
+
img.save(temp_path) # Save the image locally for further use
|
| 25 |
+
return temp_path
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"Error downloading image: {e}")
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
# Step 2: Upload Image to the API
|
| 31 |
+
def upload_image(image_path):
|
| 32 |
+
sample_file = genai.upload_file(path=image_path, display_name="Product Image")
|
| 33 |
+
print(f"Uploaded file '{sample_file.display_name}' as: {sample_file.uri}")
|
| 34 |
+
return sample_file
|
| 35 |
+
|
| 36 |
+
# Step 3: Display Image
|
| 37 |
+
def display_image(image_path):
|
| 38 |
+
img = Image.open(image_path)
|
| 39 |
+
plt.imshow(img)
|
| 40 |
+
plt.axis('off')
|
| 41 |
+
plt.show()
|
| 42 |
+
|
| 43 |
+
# Step 4: Classify image to decide whether it contains fruits/vegetables or other products
|
| 44 |
+
def classify_image(sample_file):
|
| 45 |
+
model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest")
|
| 46 |
+
response = model.generate_content([sample_file, "Does this image contain fruits or vegetables? Answer 'yes' or 'no' only."])
|
| 47 |
+
classification = response.text.strip().lower()
|
| 48 |
+
return classification == "yes"
|
| 49 |
+
|
| 50 |
+
# Step 5: Predict freshness (for fruits and vegetables)
|
| 51 |
+
def predict_freshness(sample_file):
|
| 52 |
+
model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest")
|
| 53 |
+
response = model.generate_content([sample_file, "Can you provide the average freshness index (1-10) of the fruits/vegetables in the image. Just output the number."])
|
| 54 |
+
try:
|
| 55 |
+
freshness_index = int(response.text.strip())
|
| 56 |
+
return freshness_index
|
| 57 |
+
except ValueError:
|
| 58 |
+
print("Error: Unable to convert the response to an integer.")
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
# Step 6: Generate product details (for other products)
|
| 62 |
+
def generate_product_details(sample_file):
|
| 63 |
+
model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest")
|
| 64 |
+
response = model.generate_content([sample_file,
|
| 65 |
+
f"Tell me the name of each product, its category among the following list of categories: {categories}, brand, MRP, manufacturer, expiry date, and quantity in the image. "
|
| 66 |
+
"Do not output anything else. Output format for each product: "
|
| 67 |
+
"Product Name: [Extracted Product name], Category: [Extracted Category], Brand: [Extracted Brand name], MRP: [Extracted MRP], Manufacturer: [Extracted Manufacturer name], "
|
| 68 |
+
"Expiry Date: [Extracted Expiry Date], Quantity: [Extracted Quantity]. Separate the details of each product with one newline character. "
|
| 69 |
+
"If some of the information is not available for a product, then output NA for that detail."
|
| 70 |
+
])
|
| 71 |
+
return response.text.strip() if response else ""
|
| 72 |
+
|
| 73 |
+
# Step 7: Parse the response into a DataFrame
|
| 74 |
+
def parse_response_to_dataframe(response_text):
|
| 75 |
+
columns = ["Product Name", "Category", "Brand", "MRP", "Manufacturer", "Expiry Date", "Quantity"]
|
| 76 |
+
product_sections = response_text.split("\n")
|
| 77 |
+
products_list = []
|
| 78 |
+
|
| 79 |
+
for product_section in product_sections:
|
| 80 |
+
product_details = {col: "NA" for col in columns}
|
| 81 |
+
response_parts = product_section.split(", ")
|
| 82 |
+
|
| 83 |
+
for part in response_parts:
|
| 84 |
+
if "Product Name" in part:
|
| 85 |
+
product_details["Product Name"] = part.split(": ")[1]
|
| 86 |
+
elif "Category" in part:
|
| 87 |
+
product_details["Category"] = part.split(": ")[1]
|
| 88 |
+
elif "Brand" in part:
|
| 89 |
+
product_details["Brand"] = part.split(": ")[1]
|
| 90 |
+
elif "MRP" in part:
|
| 91 |
+
product_details["MRP"] = part.split(": ")[1]
|
| 92 |
+
elif "Manufacturer" in part:
|
| 93 |
+
product_details["Manufacturer"] = part.split(": ")[1]
|
| 94 |
+
elif "Expiry Date" in part:
|
| 95 |
+
product_details["Expiry Date"] = part.split(": ")[1]
|
| 96 |
+
elif "Quantity" in part:
|
| 97 |
+
product_details["Quantity"] = part.split(": ")[1]
|
| 98 |
+
|
| 99 |
+
products_list.append(product_details)
|
| 100 |
+
|
| 101 |
+
return pd.DataFrame(products_list, columns=columns)
|
| 102 |
+
|
| 103 |
+
# Step 8: Style the DataFrame for better display
|
| 104 |
+
def style_dataframe(df):
|
| 105 |
+
return df.style.set_properties(**{'text-align': 'center', 'border': '1px solid grey'}) .set_table_styles([{'selector': 'td', 'props': [('border', '1px solid grey')]}], overwrite=False)
|
| 106 |
+
|
| 107 |
+
# Step 9: Display results (image and styled DataFrame)
|
| 108 |
+
def display_results(image_path, styled_df):
|
| 109 |
+
display_image(image_path) # Display the image
|
| 110 |
+
print("\nProduct Details:\n")
|
| 111 |
+
display(styled_df) # Display the styled DataFrame
|
| 112 |
+
|
| 113 |
+
# Step 10: Save DataFrame to CSV
|
| 114 |
+
def save_dataframe_to_csv(df, file_name="product_details.csv"):
|
| 115 |
+
df.to_csv(file_name, index=False)
|
| 116 |
+
print(f"DataFrame saved to {file_name}")
|
| 117 |
+
|
| 118 |
+
# Combined Pipeline: Choose action based on image content
|
| 119 |
+
def combined_pipeline(image_source, is_url=False):
|
| 120 |
+
# Step 1: Download the image if it's a URL
|
| 121 |
+
if is_url:
|
| 122 |
+
image_path = download_image(image_source)
|
| 123 |
+
if not image_path:
|
| 124 |
+
print("Failed to download the image.")
|
| 125 |
+
return
|
| 126 |
+
else:
|
| 127 |
+
image_path = image_source
|
| 128 |
+
|
| 129 |
+
# Step 2: Upload the image
|
| 130 |
+
sample_file = upload_image(image_path)
|
| 131 |
+
if not sample_file:
|
| 132 |
+
print("Error uploading image.")
|
| 133 |
+
return
|
| 134 |
+
|
| 135 |
+
# Step 3: Classify whether the image contains fruits/vegetables
|
| 136 |
+
is_fruits_or_vegetables = classify_image(sample_file)
|
| 137 |
+
|
| 138 |
+
if is_fruits_or_vegetables:
|
| 139 |
+
print("Image contains fruits or vegetables. Predicting freshness...")
|
| 140 |
+
freshness_index = predict_freshness(sample_file)
|
| 141 |
+
if freshness_index is not None:
|
| 142 |
+
print(f"The predicted freshness index is: {freshness_index}")
|
| 143 |
+
else:
|
| 144 |
+
print("Failed to predict freshness.")
|
| 145 |
+
else:
|
| 146 |
+
print("Image contains products. Extracting details...")
|
| 147 |
+
response_text = generate_product_details(sample_file)
|
| 148 |
+
if not response_text:
|
| 149 |
+
print("No product details generated.")
|
| 150 |
+
return
|
| 151 |
+
|
| 152 |
+
df = parse_response_to_dataframe(response_text)
|
| 153 |
+
styled_df = style_dataframe(df)
|
| 154 |
+
display_results(image_path, styled_df)
|
| 155 |
+
|
| 156 |
+
# Save the DataFrame to a CSV file
|
| 157 |
+
save_dataframe_to_csv(df, "product_details.csv")
|
| 158 |
+
|
| 159 |
+
# Download the CSV file
|
| 160 |
+
files.download("product_details.csv")
|