def _print_example(code):
    print(code)


def ex1():
    code = '''
EX1: DEEP NEURAL NETWORK

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt

x=np.array([0,1,2,3,4,5],dtype=float)
y=3*x+2

model=keras.Sequential([layers.Dense(1,input_shape=[1])])
model.compile(optimizer='adam',loss='mse')

history=model.fit(x,y,epochs=500,verbose=0)

weights=model.layers[0].get_weights()
print("Learned weight (slope):",weights[0][0][0])
print("Learned bias:",weights[1][0])

test_value=np.array([10.0])
prediction=model.predict(test_value)[0][0]
print("Prediction for x=10:",prediction)

plt.plot(history.history['loss'])
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Training Loss Curve")
plt.show()
'''
    _print_example(code)


def ex2():
    code = '''
EX2: SPEECH TO TEXT

import speech_recognition as sr

r=sr.Recognizer()

with sr.AudioFile("audio.wav") as source:
    audio=r.record(source)

try:
    text=r.recognize_google(audio)
    print("Recognized text:",text)
except sr.UnknownValueError:
    print("Sorry, could not understand the audio")
except sr.RequestError as e:
    print("Could not request results;",e)
'''
    _print_example(code)


def ex3():
    code = '''
EX3: TEXT TO SPEECH

import pyttsx3

engine=pyttsx3.init()
engine.setProperty('rate',170)
engine.setProperty('volume',0.9)

voices=engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)

text=input("Enter the text to convert to speech: ")

engine.say(text)
engine.runAndWait()
'''
    _print_example(code)


def ex4():
    code = '''
EX4: TIME SERIES FORECASTING WITH LSTM

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Dense

time=np.arange(0,100,0.1)
data=np.sin(time)

df=pd.DataFrame(data,columns=['value'])

scaler=MinMaxScaler(feature_range=(0,1))
scaled_data=scaler.fit_transform(df)

def create_sequences(data,time_step=10):
    X=[]
    y=[]
    for i in range(len(data)-time_step):
        X.append(data[i:i+time_step,0])
        y.append(data[i+time_step,0])
    return np.array(X),np.array(y)

time_step=10

X,y=create_sequences(scaled_data,time_step)
X=X.reshape(X.shape[0],X.shape[1],1)

train_size=int(len(X)*0.8)

X_train=X[:train_size]
X_test=X[train_size:]

y_train=y[:train_size]
y_test=y[train_size:]

model=Sequential()
model.add(LSTM(50,input_shape=(time_step,1)))
model.add(Dense(1))

model.compile(loss='mean_squared_error',optimizer='adam')

model.fit(X_train,y_train,epochs=10,batch_size=32)

train_predict=model.predict(X_train)
test_predict=model.predict(X_test)

train_predict=scaler.inverse_transform(train_predict)
test_predict=scaler.inverse_transform(test_predict)

print("Training complete")

plt.plot(df.values)
plt.show()
'''
    _print_example(code)


def ex5a():
    code = '''
EX5A: FEEDFORWARD NEURAL NETWORK FOR SINGLE LOGIC GATE

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Input

inputs=np.array([[0,0],[0,1],[1,0],[1,1]])

outputs=np.array([[0],[1],[1],[0]])

model=Sequential([
Input(shape=(2,)),
Dense(4,activation='relu'),
Dense(1,activation='sigmoid')
])

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])

model.fit(inputs,outputs,epochs=3000,verbose=0)

predictions=model.predict(inputs)

for i,p in enumerate(predictions):
    print(inputs[i],"=>",round(p[0]),"(raw:",p[0],")")
'''
    _print_example(code)


def ex5b():
    code = '''
EX5B: FEEDFORWARD NEURAL NETWORK FOR MULTIPLE LOGIC GATES

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Input

inputs=np.array([[0,0],[0,1],[1,0],[1,1]])

outputs=np.array([
[0,0,0],
[0,1,1],
[0,1,1],
[1,1,0]
])

model=Sequential([
Input(shape=(2,)),
Dense(6,activation='relu'),
Dense(3,activation='sigmoid')
])

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])

model.fit(inputs,outputs,epochs=4000,verbose=0)

predictions=model.predict(inputs)

for i,p in enumerate(predictions):
    print(inputs[i],"=> AND:",round(p[0]),"OR:",round(p[1]),"XOR:",round(p[2]))
'''
    _print_example(code)


def ex6a():
    code = '''
EX6A: RGB TO GRAYSCALE

from skimage import data
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

coffee=data.coffee()

plt.subplot(1,2,1)
plt.imshow(coffee)

gray_coffee=rgb2gray(coffee)

plt.subplot(1,2,2)
plt.imshow(gray_coffee,cmap="gray")

plt.show()
'''
    _print_example(code)


def ex6b():
    code = '''
EX6B: RGB TO HSV

from skimage import data
from skimage.color import rgb2hsv
import matplotlib.pyplot as plt

coffee=data.coffee()

plt.subplot(1,2,1)
plt.imshow(coffee)

hsv_coffee=rgb2hsv(coffee)

plt.subplot(1,2,2)
plt.imshow(hsv_coffee)

plt.show()
'''
    _print_example(code)


def ex6c():
    code = '''
EX6C: SUPERVISED SEGMENTATION

from skimage import data
from skimage.color import rgb2gray
import matplotlib.pyplot as plt

coffee=data.coffee()
gray_coffee=rgb2gray(coffee)

plt.figure(figsize=(15,15))

for i in range(10):

    binarized_gray=(gray_coffee>i*0.1)*1

    plt.subplot(5,2,i+1)

    plt.title("threshold>"+str(round(i*0.1,1)))

    plt.imshow(binarized_gray,cmap='gray')

plt.show()
'''
    _print_example(code)


def ex7():
    code = '''
EX7: OBJECT DETECTION USING YOLO

from ultralytics import YOLO
import cv2

model=YOLO("yolov8n.pt")

results=model("nun.jpg")

for r in results:

    img=r.plot()

    cv2.imshow("Detection Result",img)

    cv2.waitKey(0)

cv2.destroyAllWindows()
'''
    _print_example(code)


def ex8():
    code = '''
EX8: CHARACTER RECOGNITION USING CNN

import tensorflow as tf
from tensorflow.keras import layers,models
import numpy as np
import cv2
import matplotlib.pyplot as plt

(x_train,y_train),(x_test,y_test)=tf.keras.datasets.mnist.load_data()

x_train=x_train.astype('float32')/255.0
x_test=x_test.astype('float32')/255.0

x_train=x_train.reshape((len(x_train),28,28,1))
x_test=x_test.reshape((len(x_test),28,28,1))

model=models.Sequential([
layers.Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64,(3,3),activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(64,activation='relu'),
layers.Dense(10,activation='softmax')
])

model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

model.fit(x_train,y_train,epochs=5)

img=cv2.imread("number.png",cv2.IMREAD_GRAYSCALE)
img=cv2.resize(img,(28,28))

img=img.astype('float32')/255.0
img=img.reshape(1,28,28,1)

prediction=model.predict(img)

predicted_digit=np.argmax(prediction)

print("Predicted Digit:",predicted_digit)

plt.imshow(img.reshape(28,28),cmap='gray')
plt.show()
'''
    _print_example(code)


def ex9():
    code = '''
EX9: AUTOENCODER USING MNIST HANDWRITTEN DIGITS

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Input,Dense
from tensorflow.keras.models import Model

(x_train,_),(x_test,_)=mnist.load_data()

x_train=x_train.astype('float32')/255.
x_test=x_test.astype('float32')/255.

x_train=x_train.reshape((len(x_train),784))
x_test=x_test.reshape((len(x_test),784))

input_img=Input(shape=(784,))

encoded=Dense(128,activation='relu')(input_img)
encoded=Dense(64,activation='relu')(encoded)
encoded=Dense(32,activation='relu')(encoded)

decoded=Dense(64,activation='relu')(encoded)
decoded=Dense(128,activation='relu')(decoded)
decoded=Dense(784,activation='sigmoid')(decoded)

autoencoder=Model(input_img,decoded)

autoencoder.compile(optimizer='adam',loss='binary_crossentropy')

autoencoder.fit(x_train,x_train,
epochs=20,
batch_size=256,
shuffle=True,
validation_data=(x_test,x_test))

decoded_imgs=autoencoder.predict(x_test)

plt.imshow(decoded_imgs[0].reshape(28,28))
plt.show()
'''
    _print_example(code)