LordChristoff commited on
Commit
c10e38a
·
verified ·
1 Parent(s): 0835493

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -0
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import zipfile
3
+ import tensorflow as tf
4
+ import numpy as np
5
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
6
+ import os
7
+
8
+ from tqdm import tqdm
9
+
10
+ def unzip_and_load(zip_file_path, data_dir):
11
+ with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
12
+ zip_ref.extractall(data_dir)
13
+
14
+
15
+ unzip_and_load('realfake.zip', 'unzipped_data')
16
+
17
+ train_datagen = ImageDataGenerator(
18
+ rescale=1./255,
19
+
20
+ )
21
+
22
+ batch_size = 50 # Change Batch Size (Default 32)
23
+
24
+ train_generator = train_datagen.flow_from_directory(
25
+ 'unzipped_data',
26
+ target_size=(150, 150),
27
+ batch_size=batch_size,
28
+ class_mode='binary'
29
+ )
30
+
31
+ class ELM(object):
32
+ def __init__(self, input_size, output_size, hidden_size):
33
+ self.input_size = input_size
34
+ self.output_size = output_size
35
+ self.hidden_size = hidden_size
36
+
37
+ self.weight = np.random.normal(size=[self.hidden_size, self.input_size])
38
+ self.bias = np.random.normal(size=[self.hidden_size])
39
+ self.beta = np.random.normal(size=[self.hidden_size, self.output_size])
40
+
41
+ def sigmoid(self, x):
42
+ return 1.0 / (1.0 + np.exp(-x))
43
+
44
+ def relu(self, x):
45
+ return tf.nn.relu(x)
46
+
47
+ def predict(self, X):
48
+ X = tf.convert_to_tensor(X, dtype=tf.float32)
49
+ X = tf.reshape(X, [X.shape[0], -1]) # Flatten the input data
50
+ y = self.relu((X @ self.weight.T) + self.bias) @ self.beta
51
+ return y
52
+
53
+ def train(self, X, y):
54
+ X = tf.convert_to_tensor(X, dtype=tf.float32)
55
+ y = tf.convert_to_tensor(y, dtype=tf.float32)
56
+ X = tf.reshape(X, [X.shape[0], -1])
57
+ H = self.relu((X @ self.weight.T) + self.bias)
58
+ H_inv = tf.linalg.pinv(H)
59
+ # Add a new dimension to y to make it a column vector
60
+ y = tf.expand_dims(y, axis=-1) # Now y has shape (32, 1)
61
+ self.beta = H_inv @ y
62
+
63
+
64
+ loss = tf.reduce_mean(tf.square(self.predict(X) - y)) # Replace with your loss function
65
+
66
+ return loss
67
+
68
+ def calculate_loss(self, X, y): # define the missing function
69
+ X = tf.convert_to_tensor(X, dtype=tf.float32)
70
+ y = tf.convert_to_tensor(y, dtype=tf.float32)
71
+ y_pred = self.predict(X)
72
+ loss = tf.reduce_mean(tf.square(y_pred - y))
73
+ return loss
74
+
75
+
76
+ img_width = 150
77
+ img_height = 150
78
+ hidden_size = 100
79
+
80
+ elm = ELM(img_width * img_height * 3, 1, hidden_size)
81
+
82
+ num_epochs = 10 # Change the amount of Epochs (Default 10)
83
+
84
+ steps_per_epoch = len(train_generator)
85
+
86
+
87
+ for epoch in range(num_epochs):
88
+
89
+ train_generator.reset()
90
+ with tqdm(total=steps_per_epoch, desc=f"Training progress Epoch {epoch+1}/{num_epochs}", unit="batch", colour="green") as pbar:
91
+ for batch_x, batch_y in train_generator:
92
+ elm.train(batch_x, batch_y)
93
+ pbar.update(1)
94
+ pbar.set_postfix(loss=elm.calculate_loss(batch_x, batch_y))
95
+
96
+
97
+ if pbar.n == pbar.total:
98
+ break
99
+
100
+ val_datagen = ImageDataGenerator(rescale=1./255)
101
+ val_generator = val_datagen.flow_from_directory(
102
+ 'unzipped_data',
103
+ target_size=(150, 150),
104
+ batch_size=batch_size,
105
+ class_mode='binary'
106
+ )
107
+
108
+
109
+ train_acc = []
110
+ val_acc = []
111
+ losses = []
112
+
113
+ import gradio as gr
114
+ from tensorflow.keras.preprocessing.image import img_to_array
115
+ from PIL import Image
116
+ import numpy as np
117
+
118
+
119
+ def predict_image(image):
120
+ """Preprocesses and predicts on a single image."""
121
+ img_width = 150
122
+ img_height = 150
123
+ img = Image.fromarray(np.uint8(image)).convert(
124
+ "RGB"
125
+ ) # Convert to PIL Image and ensure RGB format
126
+ img = img.resize((img_width, img_height)) # Resize using PIL
127
+
128
+ if img is None:
129
+ return "Invalid image: Resizing failed"
130
+
131
+ x = img_to_array(img)
132
+ x = np.expand_dims(x, axis=0) # Add batch dimension
133
+ x = x / 255.0 # Normalize
134
+ prediction = elm.predict(x)
135
+
136
+ # Ensure prediction is a NumPy array and handle potential shape issues
137
+ prediction = np.array(prediction)
138
+ if prediction.size > 0:
139
+ # Calculate percentages based on prediction value
140
+ real_percentage = (1 - prediction.item()) * 100
141
+ fake_percentage = prediction.item() * 100
142
+ return f"Real: {real_percentage:.2f}% Generated: {fake_percentage:.2f}%"
143
+ else:
144
+ return "Prediction not available"
145
+
146
+
147
+ interface = gr.Interface(
148
+ fn=predict_image,
149
+ inputs="image",
150
+ outputs="text",
151
+ allow_flagging="manual", # Allow users to flag uncertain predictions
152
+ flagging_options=[
153
+ "incorrect",
154
+ "other",
155
+ ], # specify the options the user can select when flagging
156
+ css="""
157
+ .gradio-component-image {
158
+ width: 300px;
159
+ }
160
+ """, # Add your CSS here within the gr.Interface constructor
161
+ )
162
+
163
+ interface.launch(share=True, debug=True)
164
+