import os
import numpy as np
import tensorflow as tf
import time
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras.models import load_model
from PIL import Image

# Ladataan koulutettu malli
model_path = 'MobileNetV2_military_vehicles_model.tf'
model = load_model(model_path)

THUMBNAILS_DIR = 'thumbnails'

if not os.path.exists(THUMBNAILS_DIR):
    os.makedirs(THUMBNAILS_DIR)

def create_thumbnail(image_path, thumbnail_size=(128, 128)):
    img = Image.open(image_path)
    img.thumbnail(thumbnail_size)
    return img.convert("RGB")  # Muutetaan kuva RGB-muotoon


def generate_html(predictions, analyzed_count, elapsed_time):
    # Järjestä ennustukset confidencen mukaan suurimmasta pienimpään
    sorted_predictions = sorted(predictions, key=lambda x: x[2], reverse=True)

    html_content = f"""<html>
        <head>
            <title>Scan Results</title>
            <style>
                body {{ font-family: Arial; background-color: #F0F0F0; color: #292929; }}
                table {{ border-collapse: collapse; }}
                table, th, td {{ padding: 10px; border: 1px solid #292929; }}
            </style>
        </head>
        <body>
            <h1>Analysis results</h1>
            <p>Analyzed {analyzed_count} images in {elapsed_time:.2f} seconds.</p>
            <table>
                <tr>
                    <th>Image</th>
                    <th>Filename</th>
                    <th>Prediction</th>
                </tr>"""
    
    for prediction in sorted_predictions:
        image_path, predicted_class, confidence = prediction
        thumbnail = create_thumbnail(image_path)

        filename, file_extension = os.path.splitext(os.path.basename(image_path))
        thumbnail_filename = f"{filename}_thumb{file_extension}"
        thumbnail_path = os.path.join(THUMBNAILS_DIR, thumbnail_filename)

        thumbnail.save(thumbnail_path, "JPEG")
        html_content += f"<tr><td><img src='{thumbnail_path}'/></td><td>{filename+file_extension}</td><td>{predicted_class} with confidence {confidence:.2f}</td></tr>"

    html_content += "</table></body></html>"

    with open("results-MobileNetV2.html", "w") as f:
        f.write(html_content)

def preprocess_image(image_path):
    img = load_img(image_path, target_size=(224, 224))
    img_array = img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)
    return img_array / 255.0

def scan_directory(dir_to_scan):
    sotilaskalusto_classes = [
        'Anti-aircraft', 'Armored combat support vehicles', 'Armored personnel carriers', 
        'Infantry fighting vehicles', 'Light armored vehicles', 'Mine-protected vehicles', 
        'Prime movers and trucks', 'Self-propelled artillery', 'light utility vehicles', 'tanks'
    ]

    predictions_list = []
    analyzed_count = 0

    start_time = time.time()  # Aloita ajanotto

    for root, dirs, files in os.walk(dir_to_scan):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                analyzed_count += 1  # Lisää analysoitu kuva laskuriin
                image_path = os.path.join(root, file)
                image = preprocess_image(image_path)
                predictions = model.predict(image)
                predicted_class = sotilaskalusto_classes[np.argmax(predictions)]

                if np.max(predictions) > 0.01:
                    predictions_list.append((image_path, predicted_class, np.max(predictions)))

    elapsed_time = time.time() - start_time  # Laske kulunut aika

    generate_html(predictions_list, analyzed_count, elapsed_time)

# dir_to_scan = './mil'
dir_to_scan = './social-media'
scan_directory(dir_to_scan)
