# -*- coding: utf-8 -*-
"""Smart_door_lock

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1wmlnG3tDfHSrv9bvrnCxesrN4mApPCgl

#Preprocessing
#1. Resizing
#2. flatten


import os
import matplotlib.pyplot as plt
import numpy as np
from skimage.io import imread
from skimage.transform import resize
from skimage import exposure

target = []
images = []
flat_data = []
DATADIR = '/content/sample_data/images'
CATEGORIES = ['user', 'other']

# Preprocessing: Image Enhancement
for category in CATEGORIES:
    class_num = CATEGORIES.index(category)  # label encoding
    path = os.path.join(DATADIR, category)  # create path to use all images
    for img in os.listdir(path):
        img_array = imread(os.path.join(path, img))
        # print(img_array.shape)
        # plt.imshow(img_array)
        img_resized = resize(img_array, (150, 150, 3))  # Normalizes to 0 to 1

        # Contrast Stretching
        p2, p98 = np.percentile(img_resized, (2, 98))
        img_enhanced = exposure.rescale_intensity(img_resized, in_range=(p2, p98))

        # Histogram Equalization
        img_enhanced = exposure.equalize_hist(img_enhanced)

        flat_data.append(img_enhanced.flatten())
        images.append(img_enhanced)
        target.append(class_num)

flat_data = np.array(flat_data)
target = np.array(target)
images = np.array(images)
"""

#Preprocessing
#1. Resizing
#2. flatten


import os
import matplotlib.pyplot as plt
import numpy as np
from skimage.io import imread
from skimage.transform import resize

target = []
images = []
flat_data = []
DATADIR ='/content/sample_data/images'
CATEGORIES = ['user','other']

for category in CATEGORIES:
  class_num =CATEGORIES.index(category)#label encoding
  path =os.path.join(DATADIR,category)#create path to use all images
  for img in os.listdir(path):
      try:
        img_array = imread(os.path.join(path,img))
        #print(img_array.shape)
        #plt.imshow(img_array)
        img_resized=resize(img_array,(150,150,3))#Normalizes to 0 to 1
        flat_data.append(img_resized.flatten())
        images.append(img_resized)
        target.append(class_num)

      except:
            print(f"Unable to read image {img_path}")


flat_data =np.array(flat_data)
target =np.array(target)
images =np.array(images)

len(flat_data[0])

unique,count=np.unique(target,return_counts=True)
plt.bar(CATEGORIES,count)

# split data into Training and Testing
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(flat_data, target,
                                                    test_size=0.3, random_state=109, stratify=target)

unique_train, count_train = np.unique(y_train, return_counts=True)
print(f"Unique classes in y_train: {unique_train}")

# After the loop for reading and processing images
print(f"Total images read: {len(images)}")
print(f"Total target values: {len(target)}")

unique_classes, count_classes = np.unique(target, return_counts=True)
print(f"Unique classes in target: {unique_classes}")
print(f"Count of images per class: {count_classes}")

from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.svm import SVC

# Define the parameter grid
param_grid = [
    {'C': [1, 10, 100, 1000], 'kernel': ['linear']},
    {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
]

# Create the SVM model with probability=True
svc = SVC(probability=True)

# Create a StratifiedKFold cross-validator
cv = StratifiedKFold(n_splits=5)

# Set up the GridSearchCV with the SVM model, parameter grid, and stratified cross-validator
clf = GridSearchCV(svc, param_grid, cv=cv)

# Fit the model to the training data
clf.fit(X_train, y_train)

y_pred =clf.predict(X_test)
y_pred

y_test

from sklearn.metrics import accuracy_score, confusion_matrix

accuracy_score(y_pred,y_test)

confusion_matrix(y_pred,y_test)

# save the model using pickle library
import pickle 
pickle.dump(clf,open('img_model.p','wb'))

model=pickle.load(open('img_model.p','rb'))

from skimage.io import imread
from skimage.transform import resize
import numpy as np
import urllib.request
import requests
from google.colab import files
import matplotlib.pyplot as plt

# Ask the user to upload an image from their computer or enter a URL
while True:
  choice = input("Enter 'u' to upload an image from your computer, or 'b' to enter a URL: ")
  if choice == 'u':
    # Upload an image from the computer
    flat_data=[]
    uploaded = files.upload()
    for filename in uploaded.keys():
      img = imread(filename)
      img_resized = resize(img, (150,150,3))
      flat_data.append(img_resized.flatten())
    flat_data = np.array(flat_data)
    break

  elif choice == 'b':
    # Enter a URL to load an image from the internet
    flat_data=[]
    url = input("Please enter a valid image URL: ")
    try:
        # Check if the URL is valid and the image can be loaded
        response = requests.get(url)
        response.raise_for_status()
        img = imread(urllib.request.urlopen(url), mode='RGB')
        img_resized = resize(img, (150,150,3))
        flat_data.append(img_resized.flatten())
        flat_data = np.array(flat_data)
        break
    except:
        print("Invalid URL or unable to load the image. Please try again.")

  else:
    print("Invalid choice. Please try again.")

# Show the loaded image and make a prediction using the loaded model
y_out = model.predict(flat_data)
y_out = CATEGORIES[y_out[0]]
print(f'PREDICTED OUTPUT: {y_out}')

# Display the loaded image
if choice == 'u':
  img = imread(list(uploaded.keys())[0])
else:
  img = imread(urllib.request.urlopen(url), mode='RGB')
plt.imshow(img)

# Commented out IPython magic to ensure Python compatibility.
# %%writefile app.py
# 
# import streamlit as st
# import numpy as np
# from skimage.io import imread
# from skimage.transform import resize
# import pickle
# from PIL import Image
# st.title('Smart Door Lock Authentication')
# st.text('Upload the Image')
# model=pickle.load(open('img_model.p','rb'))
# uploaded_file =st.file_uploader("choose an image ...",type="jpg")
# 
# 
# 
#  
# if uploaded_file is not None:
# 
#   img =Image.open(uploaded_file)
#   st.image(img,caption='uploaded Image')
#   
#   if st.button('PREDICT'):
# 
# 
#     CATEGORIES = ['user','other']
# 
#     st.write('Result...')
#     flat_data=[]
#     img=np.array(img)
#     img_resized =resize(img,(150,150,3))
#     flat_data.append(img_resized.flatten())
#     flat_data=np.array(flat_data)
#     print(img.shape)
#   
#     y_out=model.predict(flat_data)
#     y_out=CATEGORIES[y_out[0]]
# 
#     st.title(f' PREDICTED OUTPUT: {y_out}')
#     q= model.predict_proba(flat_data)
#     for index, item in enumerate(CATEGORIES):
# 	    st.write(f' {item} :{q[0][index]*100}%')
#     
# 
# 
# 
# 
# 
#

!pip install streamlit

!streamlit run app.py & npx localtunnel --port 8501

