<jupyter_start><jupyter_text>Create Data<jupyter_code>f = open('/content/drive/MyDrive/Modi Real Audio/data.csv', 'w', newline='')
csvwriter = csv.writer(f)
csvwriter.writerow(["audio","target"])
def process(label,filename,target):
    label = f"/content/drive/MyDrive/Modi Real Audio/{label}"
    if os.path.exists(label) == False:
        os.mkdir(label)
 
    y, sr = librosa.load(filename)


    splitedSize = sr*5
    y_all = [ y[ x:x+splitedSize ] for x in range(0, y.shape[0], splitedSize ) ]
    y_all = y_all[:-1]

    for i in range(len(y_all)):
        scipy.io.wavfile.write(f"{label}/{filename.split('/')[-1][:-4]}_{label.split('/')[-1]}_{i}.wav", sr,y_all[i])
        csvwriter.writerow([f"{label}/{filename.split('/')[-1][:-4]}_{label.split('/')[-1]}_{i}.wav",target])
import glob
for files in glob.glob("/content/drive/MyDrive/Modi Real Audio/Fake_Audio/*"):
    process("fake",files,0)
for files in glob.glob("/content/drive/MyDrive/Modi Real Audio/Real_Audio/*"):
    process("real",files,1)
f.close()<jupyter_output><empty_output><jupyter_text>Deep Learning<jupyter_code>import pandas as pd
data = pd.read_csv("/content/drive/MyDrive/Modi Real Audio/data.csv")
audios = data.audio.values
y = data.target.values

X = []
for i in audios:

    x,sr = librosa.load(i)
    mfccs = librosa.feature.mfcc(y=x, sr=sr, n_mfcc=20)
    y_delta = librosa.feature.delta(mfccs)
    mfccs = np.vstack((mfccs,y_delta))
    X.append(mfccs)

X = np.array(X)
sum(y)
X.shape
X = X.reshape(X.shape[0],X.shape[1],X.shape[2],1)
y.shape
from sklearn.model_selection import StratifiedShuffleSplit
sss = StratifiedShuffleSplit(n_splits=2, test_size=0.15, random_state=0)
for train_index, test_index in sss.split(X, y):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    break
rlr = tf.keras.callbacks.ReduceLROnPlateau(
    monitor='val_loss', factor=0.1, patience=3, verbose=1, mode='auto',
    min_delta=0.0001, cooldown=0, min_lr=0,)

es = tf.keras.callbacks.EarlyStopping(
    monitor="val_loss", min_delta=0, patience=5,
    verbose=1, mode="auto", baseline=None, restore_best_weights=True,
)

nan = tf.keras.callbacks.TerminateOnNaN()
model = Sequential()
model.add(Conv2D(16, 3, activation='tanh', input_shape=(X.shape[1],X.shape[2],X.shape[3])))
model.add(Conv2D(32, 3,activation='tanh'))
model.add(MaxPool2D(pool_size=(2, 5)))
model.add(Conv2D(64, 3,activation='tanh'))
model.add(Conv2D(128, 3,activation='tanh'))
model.add(MaxPool2D(pool_size=(2, 5)))

model.add(Flatten())
model.add(Dense(128, activation='tanh'))
model.add(Dense(32, activation='tanh'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.SGD(learning_rate=0.01), metrics=['accuracy'])
model.summary()
history = model.fit(X_train, y_train,
                    validation_data =(X_test,y_test),
                    callbacks = [rlr,es,nan],
                    batch_size = 32,
                    epochs=50, verbose=1)
max(history.history['val_accuracy'])
Y_pred = model.predict(X_test)
y_pred = np.round(Y_pred)

print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
fpr, tpr, thresholds = roc_curve(y_test, Y_pred)
roc_auc = roc_auc_score(y_test, Y_pred)
plt.plot(fpr, tpr)
plt.title("ROC Curve")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.176539247154946, 'fraction_numerical': 0.022468631456084038, 'mean_word_length': 5.045855379188713, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '252716', 'license': 'Apache-2.0', 'n_tokens_mistral': 1410, 'n_tokens_neox': 1341, 'n_words': 205, 'path': 'Fake_Sound.ipynb', 'repo_name': 'adi2000jain/Fake-Audio-Detection', 'size': '3427'}