updated code working

This commit is contained in:
Leon Astner 2025-08-01 22:12:05 +02:00
parent 44271b7856
commit ab8a72e1c1
3 changed files with 50 additions and 32 deletions

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

View file

@ -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
@ -23,20 +17,23 @@ class PlantPredictor:
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"
try:
image = Image.open(image_path).convert("RGB")
# Basic image analysis
@ -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"""
@ -297,14 +298,22 @@ class PlantPredictor:
# Step 3: Analyze image + weather to create intelligent 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...")
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("="*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.")