updated code working
This commit is contained in:
parent
44271b7856
commit
ab8a72e1c1
3 changed files with 50 additions and 32 deletions
Binary file not shown.
BIN
test2/predicted_plant_growth.jpg
Normal file
BIN
test2/predicted_plant_growth.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 81 KiB |
|
@ -1,9 +1,3 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Complete Plant Prediction Pipeline with Open-Meteo Official Client
|
||||
Open source weather + AI image transformation
|
||||
"""
|
||||
|
||||
import openmeteo_requests
|
||||
import pandas as pd
|
||||
import requests_cache
|
||||
|
@ -22,21 +16,24 @@ class PlantPredictor:
|
|||
cache_session = requests_cache.CachedSession('.cache', expire_after=3600)
|
||||
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
|
||||
self.openmeteo = openmeteo_requests.Client(session=retry_session)
|
||||
|
||||
self.image_model = None
|
||||
|
||||
def get_current_location(self):
|
||||
"""Get current location using IP geolocation"""
|
||||
try:
|
||||
g = geocoder.ip('me')
|
||||
if g.ok:
|
||||
print(f" Location detected: {g.city}, {g.country}")
|
||||
print(f" Coordinates: {g.latlng[0]:.4f}, {g.latlng[1]:.4f}")
|
||||
print(f"📍 Location detected: {g.city}, {g.country}")
|
||||
print(f"📍 Coordinates: {g.latlng[0]:.4f}, {g.latlng[1]:.4f}")
|
||||
return g.latlng[0], g.latlng[1] # lat, lon
|
||||
else:
|
||||
print(" Could not detect location, using default (Milan)")
|
||||
print("⚠️ Could not detect location, using default (Milan)")
|
||||
self.image_model = None
|
||||
except Exception as e:
|
||||
print(f" Location detection failed: {e}, using default (Milan)")
|
||||
return 45.4642, 9.1900
|
||||
print(f"⚠️ Location detection failed: {e}, using default (Milan)")
|
||||
|
||||
self.image_model = None
|
||||
|
||||
def load_image_model(self):
|
||||
"""Load the image transformation model"""
|
||||
|
@ -135,9 +132,12 @@ class PlantPredictor:
|
|||
"""Create a detailed prompt for image transformation based on weather AND image analysis"""
|
||||
|
||||
if not plant_conditions:
|
||||
return "Show this plant after one week of growth"
|
||||
return "Show this plant after one week of growth", "generic plant", "unknown health"
|
||||
|
||||
# STEP 3A: Analyze original image
|
||||
plant_type = "generic plant"
|
||||
plant_health = "unknown health"
|
||||
|
||||
# STEP 3A: Analyze original image
|
||||
try:
|
||||
image = Image.open(image_path).convert("RGB")
|
||||
# Basic image analysis
|
||||
|
@ -158,7 +158,7 @@ class PlantPredictor:
|
|||
plant_type = "generic plant"
|
||||
plant_health = "healthy"
|
||||
|
||||
# STEP 3B: Weather analysis with plant-specific logic
|
||||
# STEP 3B: Weather analysis with plant-specific logic
|
||||
temp_avg = (plant_conditions['avg_temp_max'] + plant_conditions['avg_temp_min']) / 2
|
||||
|
||||
# Temperature effects (adjusted by plant type)
|
||||
|
@ -201,6 +201,7 @@ class PlantPredictor:
|
|||
|
||||
# STEP 3C: Create comprehensive prompt combining image + weather analysis
|
||||
prompt = f"""Transform this {plant_type} showing realistic growth after {plant_conditions['days_analyzed']} days. Current state: {plant_health}. Apply these weather effects: {temp_effect}, {water_effect}, {sun_effect}, and {uv_effect}. Show natural changes in leaf size, color saturation, stem thickness, and overall plant structure while maintaining the original composition and lighting. Weather summary: {plant_conditions['avg_temp_min']}-{plant_conditions['avg_temp_max']}°C, {plant_conditions['total_rain']}mm rain, {plant_conditions['total_sunshine_hours']}h sun"""
|
||||
return prompt, plant_type, plant_health
|
||||
|
||||
def detect_plant_type(self, image):
|
||||
"""Simple plant type detection based on image characteristics"""
|
||||
|
@ -234,7 +235,7 @@ class PlantPredictor:
|
|||
elif brightness > 100 and green_channel > 80:
|
||||
return "moderately healthy"
|
||||
else:
|
||||
return "showing some stress", plant_type, plant_health
|
||||
return "showing some stress"
|
||||
|
||||
def transform_plant_image(self, image_path, prompt):
|
||||
"""STEP 4: Generate new image based on analyzed prompt"""
|
||||
|
@ -273,11 +274,11 @@ class PlantPredictor:
|
|||
|
||||
# Auto-detect location if not provided
|
||||
if lat is None or lon is None:
|
||||
print("Auto-detecting location...")
|
||||
print(" Auto-detecting location...")
|
||||
lat, lon = self.get_current_location()
|
||||
|
||||
print(f"Starting plant prediction for coordinates: {lat:.4f}, {lon:.4f}")
|
||||
print(f"Analyzing {days} days of weather data...")
|
||||
print(f" Starting plant prediction for coordinates: {lat:.4f}, {lon:.4f}")
|
||||
print(f" Analyzing {days} days of weather data...")
|
||||
|
||||
# Step 1: Get weather data using official Open-Meteo client
|
||||
print("Fetching weather data with caching and retry...")
|
||||
|
@ -296,15 +297,23 @@ class PlantPredictor:
|
|||
print(f"\nPlant-specific weather analysis: {plant_conditions}")
|
||||
|
||||
# Step 3: Analyze image + weather to create intelligent prompt
|
||||
print("\nSTEP 3: Analyzing image and creating transformation prompt...")
|
||||
prompt, plant_type, plant_health = self.create_transformation_prompt(image_path, plant_conditions)
|
||||
print(f"Plant identified as: {plant_type}")
|
||||
print(f"Current health: {plant_health}")
|
||||
print(f"Generated transformation prompt: {prompt}")
|
||||
print("\n STEP 3: Analyzing image and creating transformation prompt...")
|
||||
try:
|
||||
prompt, plant_type, plant_health = self.create_transformation_prompt(image_path, plant_conditions)
|
||||
print(f" Plant identified as: {plant_type}")
|
||||
print(f" Current health: {plant_health}")
|
||||
print(f" Generated transformation prompt: {prompt}")
|
||||
except Exception as e:
|
||||
print(f" Error in Step 3: {e}")
|
||||
return None
|
||||
|
||||
# Step 4: Generate transformed image
|
||||
print("\nSTEP 4: Generating prediction image...")
|
||||
result_image = self.transform_plant_image(image_path, prompt)
|
||||
try:
|
||||
result_image = self.transform_plant_image(image_path, prompt)
|
||||
except Exception as e:
|
||||
print(f" Error in Step 4: {e}")
|
||||
return None
|
||||
|
||||
if result_image:
|
||||
result_image.save(output_path)
|
||||
|
@ -319,22 +328,31 @@ if __name__ == "__main__":
|
|||
# Initialize predictor
|
||||
predictor = PlantPredictor()
|
||||
|
||||
# Example coordinates (Milan, Italy)
|
||||
latitude = 45.4642
|
||||
longitude = 9.1900
|
||||
|
||||
# Predict plant growth
|
||||
# Replace 'your_plant_image.jpg' with actual image path
|
||||
result = predictor.predict_plant_growth(
|
||||
image_path="./foto/basilico.jpg",
|
||||
output_path="predicted_plant_growth.jpg",
|
||||
lat=latitude,
|
||||
lon=longitude,
|
||||
output_path="./predicted_plant_growth.jpg",
|
||||
days=7
|
||||
)
|
||||
|
||||
if result:
|
||||
image, conditions, weather_data = result
|
||||
image, conditions, weather_data, plant_type, plant_health = result
|
||||
print("\n" + "="*50)
|
||||
print("PLANT PREDICTION COMPLETED SUCCESSFULLY!")
|
||||
print(" PLANT PREDICTION COMPLETED SUCCESSFULLY!")
|
||||
print("="*50)
|
||||
print(f"Weather conditions analyzed: {conditions}")
|
||||
print(f"Weather data shape: {weather_data.shape}")
|
||||
print(f"Temperature range: {conditions['avg_temp_min']}°C to {conditions['avg_temp_max']}°C")
|
||||
print(f"Total precipitation: {conditions['total_rain']}mm")
|
||||
print(f"Sunshine hours: {conditions['total_sunshine_hours']}h")
|
||||
print(f" Plant type: {plant_type}")
|
||||
print(f" Plant health: {plant_health}")
|
||||
print(f" Weather conditions: {conditions}")
|
||||
print(f" Data points: {weather_data.shape}")
|
||||
print(f" Temperature: {conditions['avg_temp_min']}°C to {conditions['avg_temp_max']}°C")
|
||||
print(f" Total rain: {conditions['total_rain']}mm")
|
||||
print(f" Sunshine: {conditions['total_sunshine_hours']}h")
|
||||
else:
|
||||
print("Plant prediction failed.")
|
Loading…
Add table
Add a link
Reference in a new issue