Mohammedallyl commited on
Commit
c4dc0b3
1 Parent(s): 518b85d

Upload 27 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ Models/face_landmarker.task filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ WORKDIR /code
4
+
5
+ COPY ./requirements.txt /code/requirments.txt
6
+ RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
7
+ RUN pip install --no-cache-dir --upgrade -r /code/requirments.txt
8
+
9
+ COPY . .
10
+
11
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
FaceRecognition/ModelTrainer.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+
3
+ import numpy as np
4
+ from tensorflow_hub import KerasLayer
5
+ import os
6
+
7
+ from keras.layers import Dense,Dropout,Input,BatchNormalization,Lambda
8
+ from keras.models import Model
9
+ from keras.optimizers import Adam
10
+ from keras import Sequential
11
+ from keras.callbacks import EarlyStopping,ModelCheckpoint
12
+ from keras.layers.experimental.preprocessing import RandomRotation,RandomFlip,RandomCrop,PreprocessingLayer
13
+ from tensorflow.math import l2_normalize
14
+ from sys import argv
15
+
16
+ User=argv[1]
17
+
18
+ NegativeDatasetPath="./FaceRecognition/ExtactedFaces/Negative/"
19
+ TrainUsersDatasetPath="./FaceRecognition/ExtactedFaces/Train/"
20
+ TestUsersDatasetPath="./FaceRecognition/ExtactedFaces/Test/"
21
+ DatasetPath="./FaceRecognition/ExtactedFaces/Dataset/"
22
+ def DatasetPaths(UserDatapath,state,NegativeDatasetPath=None,DatasetPath=None):
23
+ User=os.listdir(UserDatapath)
24
+ UserFiles=[]
25
+ UserLabels=[]
26
+ for folder in User:
27
+ for file in os.listdir(UserDatapath+folder):
28
+ UserFiles.append(UserDatapath+folder+'/'+file)
29
+ UserLabels.append(folder)
30
+
31
+ if state==True:
32
+
33
+ Negativefiles=[]
34
+ NegativeLabels=[]
35
+ DatasetPathfiles=[]
36
+ for file in os.listdir(NegativeDatasetPath):
37
+ Negativefiles.append(NegativeDatasetPath+file)
38
+ NegativeLabels.append(file.split(",")[0])
39
+
40
+
41
+ for file in os.listdir(DatasetPath):
42
+ DatasetPathfiles.append(DatasetPath+file)
43
+
44
+
45
+ return np.array(Negativefiles),np.array(NegativeLabels),np.array(UserFiles),np.array(UserLabels),np.array(DatasetPathfiles)
46
+ return np.array(UserFiles),np.array(UserLabels)
47
+
48
+
49
+ Negativefiles,NegativeLabels,UserFiles,UserLabels,DatasetPathfiles=DatasetPaths(TrainUsersDatasetPath,True,NegativeDatasetPath,DatasetPath)
50
+ Negativefiles,NegativeLabels,UserFiles,UserLabels,DatasetPathfiles
51
+ TrainClasses=np.unique(UserLabels)
52
+ TrainClassesCount=len(TrainClasses)
53
+
54
+ TestUserFiles,TestUserLabels=DatasetPaths(UserDatapath=TestUsersDatasetPath,state=False)
55
+ TestClasses=np.unique(TestUserLabels)
56
+ TestClassesCount=len(TestClasses)
57
+
58
+ mask=np.zeros(shape=(224,224,3))
59
+ mask[:,:,0]=200
60
+ mask[:,:,1]=100
61
+ mask[:,:,2]=200
62
+ mask=tf.cast(mask/255,tf.float32)
63
+ FliPer=RandomFlip(mode="horizontal",)
64
+ Rotater=RandomRotation([-0.135,0.135])
65
+ def PreProcessInput(Image,num):
66
+ if num ==0:
67
+ Image=FliPer(Image)
68
+ elif num==1:
69
+ Image= 0.75*Image+0.25*mask
70
+ if num<=2:
71
+ return Rotater(Image)
72
+
73
+ else:
74
+ return Image
75
+
76
+ @tf.function
77
+ def load_image(Anchor,Positive,Nagative,State):
78
+
79
+ Anchor=tf.io.read_file(Anchor)
80
+ Anchor=tf.image.decode_jpeg(Anchor)
81
+ Anchor = tf.cast(Anchor, tf.float32)
82
+ Anchor = tf.image.resize(Anchor, [224,224], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR)
83
+ ranA=tf.random.uniform(shape=[1],minval=0,maxval=6,dtype=tf.int32)
84
+
85
+ Positive=tf.io.read_file(Positive)
86
+ Positive=tf.image.decode_jpeg(Positive)
87
+ Positive = tf.cast(Positive, tf.float32)
88
+ Positive = tf.image.resize(Positive, [224,224], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR)
89
+ ranB=tf.random.uniform(shape=[1],minval=0,maxval=6,dtype=tf.int32)
90
+
91
+ Negative=tf.io.read_file(Nagative)
92
+ Negative=tf.image.decode_jpeg(Negative)
93
+ Negative = tf.cast(Negative, tf.float32)
94
+ Negative = tf.image.resize(Negative, [224,224], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR)
95
+ ranN=tf.random.uniform(shape=[1],minval=0,maxval=6,dtype=tf.int32)
96
+ if State:
97
+ Anchor=PreProcessInput(Anchor/255,ranA)
98
+ Positive=PreProcessInput(Positive/255,ranB)
99
+ Negative=PreProcessInput(Negative/255,ranN)
100
+ else:
101
+ Anchor=Anchor/255
102
+ Positive=Positive/255
103
+ Negative=Negative/255
104
+
105
+ return (Anchor,Positive,Negative)
106
+
107
+
108
+ def DatasetTripletsGenerator(State):
109
+ # Negativefiles=Negativefiles
110
+ # NegativeLabels=NegativeLabels
111
+ # DatasetPathfiles=DatasetPathfiles
112
+ if State:
113
+ UsersImagesPath=UserFiles
114
+ UsersImagesLabel=UserLabels
115
+ ClassesCount=TrainClassesCount
116
+ Classes=TrainClasses
117
+
118
+ else:
119
+ ImagesName=TestUserFiles
120
+ ImagesLabel=TestUserLabels
121
+ ClassesCount=TestClassesCount
122
+ Classes=TestClasses
123
+
124
+
125
+
126
+ for i in range(ClassesCount):
127
+ class_=Classes[i]
128
+ files=UsersImagesPath[UsersImagesLabel==class_]
129
+
130
+ files_num=len(files)
131
+ for index in range(files_num-1):
132
+ for j in range(index+1,files_num):
133
+ ancore=files[index]
134
+ positive=files[j]
135
+ random=np.random.randint(0,high=10)
136
+ negative=None
137
+ if random<=3:
138
+ negative=Negativefiles[NegativeLabels==class_]
139
+ if type(negative)==list:
140
+ negative=np.random.choice(negative)
141
+ elif random<=7:
142
+ negative=UsersImagesPath[UsersImagesLabel != class_]
143
+ if type(negative)==list:
144
+ negative=np.random.choice(negative)
145
+
146
+ elif random<=10:
147
+ negative=DatasetPathfiles
148
+ if type(negative)==list:
149
+ negative=np.random.choice(negative)
150
+
151
+ if type(negative)!=str:
152
+ negative=np.random.choice(DatasetPathfiles)
153
+
154
+
155
+
156
+
157
+ yield ancore,positive,negative,State
158
+
159
+
160
+ @tf.function
161
+ def EmbeddingImageLoader(Anchor,Label):
162
+
163
+ Anchor=tf.io.read_file(Anchor)
164
+ Anchor=tf.image.decode_jpeg(Anchor)
165
+ Anchor = tf.cast(Anchor, tf.float32)
166
+ Anchor = tf.image.resize(Anchor, [224,224], method = tf.image.ResizeMethod.NEAREST_NEIGHBOR)
167
+
168
+ Anchor=Anchor/255
169
+
170
+
171
+ return (Anchor,Label)
172
+
173
+
174
+ TrainData=tf.data.Dataset.from_generator(DatasetTripletsGenerator,args=[True],output_types=(tf.string,tf.string,tf.string,tf.bool),output_shapes=((),(),(),()),name="DataLoaderPipeline")
175
+ TrainData=TrainData.map(load_image)
176
+ TrainData=TrainData.batch(2).shuffle(buffer_size=10)
177
+
178
+ TestData=tf.data.Dataset.from_generator(DatasetTripletsGenerator,args=[False],output_types=(tf.string,tf.string,tf.string,tf.bool),output_shapes=((),(),(),()),name="DataLoaderPipeline")
179
+ TestData=TestData.map(load_image).batch(2)
180
+
181
+ EmbeddingData=tf.data.Dataset.from_tensor_slices((list(UserFiles),list(UserLabels))).map(EmbeddingImageLoader).batch(1)
182
+
183
+
184
+ class DistanceLayer(tf.keras.layers.Layer):
185
+ def __init__(self):
186
+ super().__init__()
187
+ def call(self,anchor,positive,negative):
188
+ dis_ap=tf.reduce_sum(tf.square(anchor - positive), 1) ## distance between anchor and positive
189
+ dis_an=tf.reduce_sum(tf.square(anchor - negative), 1) ## distance between anchor and negative
190
+ return dis_ap , dis_an
191
+
192
+ def GetEncoder():
193
+ # /drive/MyDrive/Model/
194
+ if os.path.isdir("./FaceRecognition/FaceModel/keras/"):
195
+ return tf.keras.models.load_model("./FaceRecognition/FaceModel/")
196
+ else:
197
+ pretrained_model = KerasLayer("./prtrained/archive/",trainable=False) ##pretraind Model
198
+
199
+ encode_model = Sequential([
200
+ pretrained_model,
201
+ Dropout(0.2),
202
+ Dense(512, activation='relu'),
203
+ BatchNormalization(),
204
+ Dense(128, activation="relu"),
205
+ Lambda(lambda x:l2_normalize(x))
206
+ ], name="Encoder")
207
+ return encode_model
208
+ def SiameseNetwork(inputshape=(224,224,3)):
209
+ An_input=Input(shape=inputshape)
210
+
211
+ Po_input=Input(shape=inputshape)
212
+
213
+ Ne_input=Input(shape=inputshape)
214
+
215
+ encoder=GetEncoder()
216
+
217
+ An_embeding=encoder(An_input)
218
+ Po_embeding=encoder(Po_input)
219
+ Ne_embeding=encoder(Ne_input)
220
+
221
+
222
+ distanc=DistanceLayer()(An_embeding,Po_embeding,Ne_embeding) #return distance between (A and B) and (A and N)
223
+
224
+ return Model(inputs=[An_input,Po_input,Ne_input],outputs=distanc)
225
+
226
+
227
+
228
+
229
+ siames_net=SiameseNetwork()
230
+ class SiamesModel(Model):
231
+ def __init__(self,siames_net,DesiredDistance):
232
+ super(SiamesModel, self).__init__()
233
+
234
+ self.Model=siames_net
235
+ self.DesiredDistance=DesiredDistance
236
+ self.LossTracker=tf.keras.metrics.Mean(name="Loss")
237
+
238
+ self.VALTracker=tf.keras.metrics.Mean(name="VAL")
239
+
240
+ self.PmeanTracker=tf.keras.metrics.Mean(name="P_mean")
241
+
242
+ self.PmaxTracker=tf.keras.metrics.Mean(name="P_max")
243
+
244
+ self.PstdTracker=tf.keras.metrics.Mean(name="P_std")
245
+
246
+ self.FARTracker=tf.keras.metrics.Mean(name="FAR")
247
+
248
+ self.N_meanTracker=tf.keras.metrics.Mean(name="N_mean")
249
+
250
+ self.NstdTracker=tf.keras.metrics.Mean(name="N_std")
251
+ self.NminTracker=tf.keras.metrics.Mean(name="N_min")
252
+
253
+ def call(self,data):
254
+ return self.Model(data)
255
+
256
+ def train_step(self,data):
257
+ with tf.GradientTape() as Tape:
258
+ AP_distanc,AN_distance=self.Model(data)
259
+ loss=self.TripLoss(AP_distanc,AN_distance)
260
+ gradients=Tape.gradient(loss,self.Model.trainable_weights)
261
+ self.optimizer.apply_gradients(zip(gradients, self.Model.trainable_weights))
262
+ self.DistanceEval(AP_distanc,AN_distance)
263
+ self.LossTracker.update_state(loss)
264
+ return {"VAL":self.VALTracker.result(),
265
+ "P_mean":self.PmeanTracker.result(),
266
+ "P_max":self.PmaxTracker.result(),
267
+ "P_std":self.PstdTracker.result(),
268
+ "FAR":self.FARTracker.result(),
269
+ "N_mean":self.N_meanTracker.result(),
270
+ "N_min":self.NminTracker.result(),
271
+ "N_std":self.NstdTracker.result(),
272
+ "Loss":self.LossTracker.result()}
273
+
274
+
275
+ def test_step(self, data):
276
+ AP_distanc,AN_distance=self.Model(data)
277
+ loss=self.TripLoss(AP_distanc,AN_distance)
278
+ self.LossTracker.update_state(loss)
279
+ self.DistanceEval(AP_distanc,AN_distance)
280
+ return {"VAL":self.VALTracker.result(),
281
+ "P_mean":self.PmeanTracker.result(),
282
+ "P_max":self.PmaxTracker.result(),
283
+ "P_std":self.PstdTracker.result(),
284
+ "FAR":self.FARTracker.result(),
285
+ "N_mean":self.N_meanTracker.result(),
286
+ "N_min":self.NminTracker.result(),
287
+ "N_std":self.NstdTracker.result(),
288
+ "Loss":self.LossTracker.result()}
289
+
290
+
291
+
292
+ def TripLoss(self,ap_distance,an_distance):
293
+ return tf.reduce_mean(tf.maximum(ap_distance-0.2*self.DesiredDistance,0)+tf.maximum(self.DesiredDistance-an_distance, 0.0))
294
+
295
+
296
+ @property
297
+ def metrics(self):
298
+ return [self.LossTracker,self.VALTracker,self.PmaxTracker,self.PmeanTracker,self.PstdTracker,self.FARTracker,self.N_meanTracker,self.NminTracker,self.NstdTracker]
299
+
300
+ def DistanceEval(self,P_distance,N_distance):
301
+
302
+ P_pred,N_pred=self.TDEvaluation(P_distance,N_distance)
303
+ PCDCount=tf.size(tf.where(P_pred))
304
+
305
+ VAL=PCDCount/tf.size(P_pred)
306
+ self.VALTracker.update_state(VAL)
307
+
308
+ NCDcount=tf.size(tf.where(N_pred))
309
+ FAR=1-(NCDcount/tf.size(P_pred))
310
+ self.FARTracker.update_state(FAR)
311
+ P_mean=tf.reduce_mean(P_distance)
312
+ self.PmeanTracker.update_state(P_mean)
313
+ N_mean=tf.reduce_mean(N_distance)
314
+ self.N_meanTracker.update_state(N_mean)
315
+ P_std=tf.math.reduce_std(P_distance)
316
+ self.PstdTracker.update_state(P_std)
317
+ N_std=tf.math.reduce_std(N_distance)
318
+ self.NstdTracker.update_state(N_std)
319
+ P_max=tf.reduce_max(P_distance)
320
+ self.PmaxTracker.update_state(P_max)
321
+ N_min=tf.reduce_min(N_distance)
322
+ self.NminTracker.update_state(N_min)
323
+
324
+ def TDEvaluation(self,P_distance,N_distance):
325
+ return tf.cast(P_distance<=self.DesiredDistance,dtype=tf.int8),tf.cast(N_distance>self.DesiredDistance,dtype=tf.int8)
326
+
327
+
328
+ DesiredDistance=1
329
+ Optimizer= Adam(learning_rate=1e-4)
330
+ Siamesmodel=SiamesModel(siames_net,DesiredDistance)
331
+ Siamesmodel.compile(optimizer=Adam(1e-4),weighted_metrics=[])
332
+ Siamesmodel.fit(TrainData,validation_data=TestData,epochs=1,callbacks=[EarlyStopping(patience=3),ModelCheckpoint(f"./FaceRecognition/FaceModel/{User}/kerasModel")])
333
+
334
+
335
+
336
+ def EmbeddingMaker(DataPipline,Model):
337
+ Embedding={}
338
+ NamesTimer={}
339
+ for Image,Name in DataPipline:
340
+ Name=str(Name[0].numpy())[2:-1]
341
+
342
+ if Name[0] not in Embedding.keys():
343
+ NamesTimer[Name]=1
344
+ Embedding[Name]=tf.squeeze(Model(Image)).numpy()
345
+
346
+ else:
347
+ Embedding[Name]=Embedding[Name]+tf.squeeze(Model(Image)).numpy()
348
+ NamesTimer[Name]=NamesTimer[Name]+1
349
+ for Name in Embedding:
350
+ Embedding[Name]=Embedding[Name]/NamesTimer[Name]
351
+ return Embedding
352
+
353
+
354
+ Embedding=EmbeddingMaker(EmbeddingData,siames_net.layers[3])
355
+ EmbeddingLabel,EmbeddingNames=[[Embedding[Name] for Name in Embedding] , {Name:Index+1 for Index,Name in enumerate(Embedding) } ]
356
+
357
+
358
+
359
+ class LiteModel(tf.Module):
360
+ def __init__(self,FaceModel,FacesEmbedding,name="FaceLiteModel"):
361
+ self.FaceModel=FaceModel
362
+ self.FacesEmdedding=FacesEmbedding
363
+
364
+ @tf.function(input_signature=[tf.TensorSpec(shape=[None,224,224,3],dtype=tf.float32),tf.TensorSpec(shape=[],dtype=tf.float32)])
365
+ def __call__(self,Image,Threshold):
366
+ Embedding=self.FaceModel(Image)
367
+ Distance=tf.cast(Threshold,tf.float32)
368
+ Name=0
369
+ for Index,StoredEmbedding in enumerate(self.FacesEmdedding):
370
+ distance=tf.reduce_sum(tf.math.pow(Embedding-StoredEmbedding,2))
371
+ if distance<Distance:
372
+ Name=Index+1
373
+ Distance=distance
374
+ return Name,Distance
375
+
376
+ litemodel=LiteModel(siames_net.layers[3],FacesEmbedding=EmbeddingLabel)
377
+
378
+
379
+ converter=tf.lite.TFLiteConverter.from_concrete_functions([litemodel.__call__.get_concrete_function()],litemodel)
380
+ converter.optimizations=[tf.lite.Optimize.DEFAULT]
381
+ converter.target_spec.supported_types=[tf.float16]
382
+ tflitemodel=converter.convert()
383
+
384
+ with open(f"./FaceRecognition/FaceModel/{User}/FaceXModel.tflite","wb") as file:
385
+ file.write(tflitemodel)
IndoorLocalization/IndoorlocalizationTrainer.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from tensorflow.data import Dataset
4
+ from tensorflow import lite,float16,random,where,cast,float32,constant,reshape
5
+ from sklearn.model_selection import train_test_split
6
+ from os.path import isdir
7
+ import os
8
+ from keras.callbacks import EarlyStopping,ModelCheckpoint
9
+ from keras.models import Model,load_model
10
+ from keras.layers import Layer,Dense,Dropout,Input,Embedding,Concatenate
11
+ from keras.optimizers import Adam
12
+ from keras.losses import mean_absolute_error
13
+ from keras.metrics import R2Score
14
+ import sys
15
+ User=sys.argv[1]
16
+ print(sys.argv[0])
17
+ Data=pd.read_csv(f"./IndoorLocalization/Data/{User}/Data.csv")
18
+ print(Data)
19
+ PhonsId=np.sort(Data["PHONEID"].unique())
20
+ phoneidMap={phoneid:i for i,phoneid in enumerate(PhonsId)}
21
+ def ReplaceId(id):
22
+ if (np.random.randint(low=0,high=20,size=1)==3):
23
+ return len(phoneidMap)
24
+ return phoneidMap[id]
25
+
26
+ Data["PHONEID"]=Data["PHONEID"].apply(ReplaceId)
27
+ Data=Data.dropna()
28
+
29
+ def CleanTrainData(df):
30
+ target=df[["SPACEID","LONGITUDE","LATITUDE"]]
31
+ df=df.drop(['LONGITUDE', 'LATITUDE',"SPACEID"], axis=1)
32
+ return df, target
33
+
34
+ DataX,TargetY=CleanTrainData(Data)
35
+
36
+ LONGITUDEMax=TargetY["LONGITUDE"].max()
37
+ LATITUDEMax=TargetY["LATITUDE"].max()
38
+ LONGITUDEMin=TargetY["LONGITUDE"].min()
39
+ LATITUDEMin=TargetY["LATITUDE"].min()
40
+ BuildingWidth=20
41
+ BuildingLength=20
42
+
43
+
44
+ def LONGITUDE_min_max_newrange(item):
45
+ return ((item-LONGITUDEMin)/(LONGITUDEMax-LONGITUDEMin))*BuildingWidth
46
+
47
+ def LATITUDE_min_max_newrange(item):
48
+ return ((item-LATITUDEMin)/(LATITUDEMax-LATITUDEMin))*BuildingLength
49
+
50
+ TargetY["LONGITUDE"]=TargetY["LONGITUDE"].apply(LONGITUDE_min_max_newrange)
51
+ TargetY["LATITUDE"]=TargetY["LATITUDE"].apply(LATITUDE_min_max_newrange)
52
+
53
+ X_train, X_test, y_train, y_test = train_test_split(DataX.values,TargetY.values[:,1:], test_size=0.2, random_state=42,shuffle=True,stratify=TargetY.values[:,0])
54
+ SPACESGroups=TargetY.groupby("SPACEID")
55
+ SPACESGroupsmean=SPACESGroups.mean()
56
+ SPACEIDPosition={f"{SPACEID}":(SPACESGroupsmean.query(f"SPACEID=={SPACEID}")["LONGITUDE"].values[0],SPACESGroupsmean.query(f"SPACEID=={SPACEID}")["LATITUDE"].values[0]) for SPACEID in list(SPACESGroups.groups.keys()) }
57
+
58
+ SPACEIDPositionArray=np.array([list(SPACEIDPosition[f"{i}"]) for i in SPACESGroups.groups.keys()])
59
+ PlacesNumber=len(np.unique(TargetY.iloc[:,0]))
60
+ PhonesNumber=np.unique(DataX["PHONEID"]).size
61
+
62
+
63
+ def ApplyNormalizationthenNois(X,Phoneid,Y):
64
+ X=cast(X,dtype=float32)
65
+ Y=cast(Y,dtype=float32)
66
+ additem=np.random.choice([0,1,2])
67
+ Nuknow=np.random.randint(0,high=5,size=1)
68
+ X=(X+100)/200
69
+ if additem ==1:
70
+ if Nuknow==0:
71
+ return (X,0),Y
72
+ return (X,Phoneid),Y
73
+
74
+ else:
75
+ noise=random.normal(shape=X.shape,mean=0,stddev=0.1,dtype=float32)
76
+ NoisedX=X+noise
77
+ NoisedX=where(NoisedX<0,x=0.0,y=NoisedX)
78
+ NoisedX=where(NoisedX>1,x=1.0,y=NoisedX)
79
+ if Nuknow==0:
80
+ return (NoisedX,0),Y
81
+ return (NoisedX,Phoneid),Y
82
+
83
+ def ApplyNormalizationOnly(X,Phoneid,Y):
84
+ X=cast(X,dtype=float32)
85
+ Y=cast(Y,dtype=float32)
86
+ X=(X+100)/200
87
+ if Phoneid ==1:
88
+ return (X,1),Y
89
+ elif Phoneid ==2:
90
+ return (X,2),Y
91
+ else:
92
+ return (X,0),Y
93
+
94
+ TrainDataPipeline=Dataset.from_tensor_slices((X_train[:,:-1],X_train[:,-1],y_train)).map(ApplyNormalizationthenNois).batch(100)
95
+
96
+ TestDataPipeline=Dataset.from_tensor_slices((X_test[:,:-1],X_test[:,-1],y_test)).map(ApplyNormalizationOnly).batch(10)
97
+
98
+ class PositionAproxmator(Layer):
99
+ def __init__(self,PlacesPosition,name="PositionAproxmator"):
100
+ super(PositionAproxmator,self).__init__()
101
+ self.PlacesPosition=constant(PlacesPosition,dtype=float32,name="PlacesPositions")
102
+ def build(self,inputs_shape):
103
+ self.W=self.add_weight(shape=(inputs_shape[1],2),trainable=True,dtype=float32,name="PlacesWeight")
104
+
105
+ def call(self,Probilites):
106
+ return Probilites@(self.PlacesPosition+self.W)
107
+
108
+
109
+
110
+ def MakeModel(SPACEIDPosition,PhonesNumber):
111
+ if isdir(f"./IndoorLocalization/IndoorModels/{User}/kerasModel"):
112
+ return load_model(f"./IndoorLocalization/IndoorModels/{User}/kerasModel")
113
+ WiFiReadings=Input(168)
114
+ Phoneid=Input(1)
115
+ Embeding=Embedding(PhonesNumber,64, embeddings_regularizer="l2")(Phoneid)
116
+ X=Dense(128,activation="relu")(WiFiReadings)
117
+ X=Dropout(0.2)(X)
118
+ z=Dense(64,activation="relu")(X)
119
+ X=z+reshape(Embeding,shape=(-1,64))
120
+ X=Concatenate()([z,X,reshape(Embeding,shape=(-1,64))])
121
+ X=Dropout(0.2)(X)
122
+ X=Dense(100,activation="relu", kernel_regularizer="l2")(X)
123
+ X=Dropout(0.1)(X)
124
+ X=Dense(64,activation="relu")(X)
125
+ X=X+z
126
+ X=Dense(64,activation="relu")(X)
127
+ X=Dropout(0.2)(X)
128
+ X=Dense(PlacesNumber,activation="softmax")(X)
129
+ X=PositionAproxmator(SPACEIDPosition)(X)
130
+
131
+ return Model(inputs=[WiFiReadings,Phoneid],outputs=[X])
132
+
133
+ model=MakeModel(SPACEIDPositionArray,PhonesNumber)
134
+ model.compile(optimizer=Adam(learning_rate=1e-4),loss=mean_absolute_error,metrics=[R2Score()])
135
+ hsitory=model.fit(TrainDataPipeline,validation_data=TestDataPipeline,epochs=5,callbacks=[EarlyStopping(patience=3),ModelCheckpoint(f"./IndoorLocalization/IndoorModels/{User}/kerasModel")])
136
+ # hsitory=model.fit(TrainDataPipeline,validation_data=TestDataPipeline,epochs=5,callbacks=[EarlyStopping(patience=3),ModelCheckpoint(r"C:\Users\mf\Desktop\AIProjects")])
137
+
138
+ converter=lite.TFLiteConverter.from_keras_model(model)
139
+ converter.optimizations=[lite.Optimize.DEFAULT]
140
+ converter.target_spec.supported_types=[float16]
141
+ tflitemodel=converter.convert()
142
+ with open(f"./IndoorLocalization/IndoorModels/{User}/FinalHistoryModel.tflite","wb") as file:
143
+ file.write(tflitemodel)
Logic/FUsers/AddUser.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,File,Form,UploadFile
2
+ import sqlite3
3
+ from passlib.context import CryptContext
4
+ from os import makedirs
5
+ from os.path import exists
6
+ from pydantic import BaseModel
7
+ from PIL import Image
8
+ from io import BytesIO
9
+ UserAddRouter=APIRouter(prefix="/Users")
10
+
11
+
12
+
13
+ @UserAddRouter.post("/AddUser")
14
+ def adduser(AdminEmail:str=Form(...),AdminPassword:str =Form(...),Email:str=Form(...),Name:str=Form(...),Job:str=Form(...),Phonenumber:str=Form(...),Place:str=Form(...),BDay:str=Form(...),Password:str=Form(...),Images:UploadFile=File(...)):
15
+ try:
16
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
17
+ AdminPassword="$2b$12$33H14GFBvtomzLrEaM6Tqu7Jr621eHlXL9TVtdPU6YCljxc4eug2a"
18
+ if AdminEmail !="[email protected]":
19
+ if not pwd_context.verify( AdminPassword,AdminPassword):
20
+ return {"Status":False,"Message":" Admin Email or Password is not correct "}
21
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
22
+ UserId=0
23
+ connect=sqlite3.connect("DataBase/DataBase.bd")
24
+ cursor=connect.execute(f'''
25
+ SELECT UserId FROM Users where Email='{ Email}'
26
+ ''')
27
+ Data=cursor.fetchall()
28
+ if len(Data)==1:
29
+ if (Data[0]!=None):
30
+ return {"Status":False,"Message":"Email Is Alread Exists"}
31
+ cursor=connect.execute('''
32
+ SELECT MAX(UserId) FROM Users
33
+ ''')
34
+ Data=cursor.fetchall()
35
+
36
+ if len(Data)!=0:
37
+ if Data[0][0]==None:
38
+ UserId=0
39
+ else:
40
+ UserId=Data[0][0]+1
41
+
42
+ HashedPassword=pwd_context.hash( Password)
43
+
44
+ connect.execute(f'''
45
+ INSERT INTO Users (UserId ,Email ,UserName ,Job, Phonenumber ,Place,BDay ,Password ) VALUES ({UserId},'{ Email}','{ Name}','{ Job}', '{ Phonenumber}' ,'{ Place}','{ BDay}','{HashedPassword}')
46
+ ''')
47
+ connect.commit()
48
+ connect.close()
49
+ if (not exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train")):
50
+ makedirs(f"./FaceRecognition/ExtactedFaces/{UserId}/Train")
51
+ if (not exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/Negative")):
52
+ makedirs(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/Negative")
53
+ if (not exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Test")):
54
+ makedirs(f"./FaceRecognition/ExtactedFaces/{UserId}/Test")
55
+ if (not exists(f"./FaceRecognition/FaceModel/{UserId}")):
56
+ makedirs(f"./FaceRecognition/FaceModel/{UserId}")
57
+ if (not exists(f"./static/{UserId}")):
58
+ makedirs(f"./static/{UserId}")
59
+ Image.open(BytesIO(Images.file.read())).save(f"./static/{UserId}/user.png","PNG")
60
+ if (not exists(f"./IndoorLocalization/Data/{UserId}")):
61
+ makedirs(f"./IndoorLocalization/Data/{UserId}")
62
+ if (not exists(f"./IndoorLocalization/IndoorModels/{UserId}")):
63
+ makedirs(f"./IndoorLocalization/IndoorModels/{UserId}")
64
+
65
+ return {"Status":True,"Message":"User Is Added Correctly"}
66
+
67
+ except Exception as e :
68
+ return {"Status":False,"Message":e}
Logic/FUsers/AddUserItem.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,File,Form,UploadFile
2
+ import sqlite3
3
+
4
+ from os.path import exists
5
+ from os import makedirs
6
+
7
+ from PIL import Image
8
+ from io import BytesIO
9
+
10
+ UserItemAddRouter=APIRouter(prefix="/Users")
11
+ @UserItemAddRouter.post("/AddUserItem")
12
+ def adduser(Email:str=Form(...),Name:str=Form(...),Password:str=Form(...),Images:UploadFile=File(...)):
13
+ try:
14
+
15
+ State=False
16
+ connect=sqlite3.connect("DataBase/DataBase.bd")
17
+ cursor=connect.execute(f'''
18
+ SELECT UserId,Password FROM Users where Email='{ Email}'
19
+ ''')
20
+
21
+ FData=cursor.fetchall()
22
+
23
+
24
+
25
+ if len(FData) !=0 :
26
+ if FData[0][0]==None:
27
+ return {"Status":False,"Message":"Email or Password Is Incorrect "}
28
+ HasedPassword=FData[0][1]
29
+ UserId=FData[0][0]
30
+ State= Password==HasedPassword
31
+
32
+ Name= Name
33
+ if not State:
34
+ return {"Status":False,"Message":"Email or Password is not correct"}
35
+
36
+ if not exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{Name}"):
37
+ connect.execute(f'''
38
+ INSERT INTO UserItems (UserId ,UserItemName ) VALUES ({UserId},'{Name}')
39
+ ''')
40
+ connect.commit()
41
+ if not exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{Name}"):
42
+ makedirs(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{Name}")
43
+ if not exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Test/{Name}"):
44
+ makedirs(f"./FaceRecognition/ExtactedFaces/{UserId}/Test/{Name}")
45
+ if not exists(f"./static/{UserId}/{Name}"):
46
+ makedirs(f"./static/{UserId}/{Name}")
47
+ Image.open(BytesIO(Images.file.read())).save(f"./static/{UserId}/{Name}/user.png","PNG")
48
+ return {"Status":True,"Message":"User Is Added Correctly"}
49
+ else:
50
+ return {"Status":False,"Message":"Name Is Already Exist"}
51
+ except Exception as e:
52
+ return {"Status":False,"Message":e}
Logic/FUsers/DeleteUser.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ import sqlite3
3
+ from passlib.context import CryptContext
4
+ from shutil import rmtree
5
+ from os.path import exists
6
+ DeleteUserRouter=APIRouter(prefix="/Users")
7
+ @DeleteUserRouter.post("/DeleteUser")
8
+ def SpeachToTextEndPoint(Email:str,Password:str,AdminEmail:str,AdminPassword:str):
9
+ try:
10
+ if AdminEmail !="[email protected]" and AdminPassword !="#mohammed*123#":
11
+ return {"Status":False,"Message":" Admin Email or Password is not correct "}
12
+ State=False
13
+
14
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
15
+
16
+
17
+ connect=sqlite3.connect("DataBase/DataBase.bd")
18
+ cursor=connect.execute(f'''
19
+ SELECT UserId,Password FROM Users where Email='{Email}'
20
+ ''')
21
+ Data=cursor.fetchall()
22
+ if len(Data) !=0 :
23
+ if Data[0][0]==None:
24
+ return {"Status":True,"Message":"User Is Not Defined Before"}
25
+ HasedPassword=Data[0][1]
26
+ UserId=Data[0][0]
27
+ State=pwd_context.verify(Password,HasedPassword)
28
+
29
+ if State:
30
+ connect.execute(f'''
31
+ DELETE FROM Users where Email='{Email}'
32
+ ''')
33
+ connect.execute(f'''
34
+ DELETE FROM UserItems WHERE UserId={UserId}
35
+ ''')
36
+ connect.commit()
37
+ if exists(f"./FaceRecognition/ExtactedFaces/{UserId}"):
38
+ rmtree(f"./FaceRecognition/ExtactedFaces/{UserId}")
39
+ return {"Status":True,"Message":"User Is Deleted Correctly"}
40
+ else:
41
+ return {"Status":False,"Message":"Email or Password is not correct"}
42
+
43
+
44
+
45
+ except sqlite3.Error as e:
46
+ return {"Status":False,"Message":e}
Logic/FUsers/DeleteUserItem.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ import sqlite3
3
+ from passlib.context import CryptContext
4
+ from shutil import rmtree
5
+ from os.path import exists
6
+ from pydantic import BaseModel
7
+ class DataType(BaseModel):
8
+ Email:str
9
+ Name:str
10
+ Password:str
11
+ UserItemDeleteRouter=APIRouter(prefix="/Users")
12
+ @UserItemDeleteRouter.post("/DeleteUserItem")
13
+ def adduser(Dat:DataType):
14
+ try:
15
+
16
+ State=False
17
+ connect=sqlite3.connect("DataBase/DataBase.bd")
18
+ cursor=connect.execute(f'''
19
+ SELECT UserId,Password FROM Users where Email='{Dat.Email}'
20
+ ''')
21
+
22
+ Data=cursor.fetchall()
23
+ if len(Data) !=0 :
24
+ if Data[0][0]==None:
25
+ return {"Status":False,"Message":"Email or Password Is Incorrect"}
26
+ HasedPassword=Data[0][1]
27
+ UserId=Data[0][0]
28
+ State=Dat.Password==HasedPassword
29
+
30
+ if not State:
31
+ return {"Status":False,"Message":"Email or Password is not correct"}
32
+ Name=Dat.Name
33
+ connect.execute(f'''
34
+ DELETE FROM UserItems WHERE UserId={UserId} AND UserItemName='{Name}'
35
+ ''')
36
+
37
+ connect.commit()
38
+ if exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Test/{Name}"):
39
+ rmtree(f"./FaceRecognition/ExtactedFaces/{UserId}/Test/{Name}")
40
+ if exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{Name}"):
41
+ rmtree(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{Name}")
42
+ else:
43
+ return {"Status":False,"Message":"User Is Not Founded"}
44
+ return {"Status":True,"Message":"User Is Deleted Correctly"}
45
+ except sqlite3.Error as e:
46
+ return {"Status":False,"Message":e}
Logic/FUsers/GetAllUsers.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import JSONResponse
3
+ import sqlite3
4
+ from pydantic import BaseModel
5
+ class DataType(BaseModel):
6
+ AdminEmail:str
7
+ AdminPassword:str
8
+ GetUserRouter=APIRouter(prefix="/Users")
9
+ @GetUserRouter.post("/GetAllUsers")
10
+ def adduser(Data:DataType):
11
+ try:
12
+ AdminPassword="$2b$12$33H14GFBvtomzLrEaM6Tqu7Jr621eHlXL9TVtdPU6YCljxc4eug2a"
13
+ if Data.AdminEmail =="[email protected]":
14
+ if not (Data.AdminPassword==AdminPassword):
15
+ response=JSONResponse({"Status":False},status_code=200)
16
+
17
+ return response
18
+ connect=sqlite3.connect("DataBase/DataBase.bd")
19
+ cursor=connect.execute(f'''
20
+ SELECT * FROM Users
21
+ ''')
22
+
23
+ Data=cursor.fetchall()
24
+ return {"Status":True,"Data":Data}
25
+ else:
26
+ response=JSONResponse({"Status":False,"Message":"Email Or password is in corredct try to login again"},status_code=200)
27
+
28
+ return response
29
+
30
+ except Exception as e:
31
+ return {"Status":False,"Message":e}
Logic/FUsers/GetUserData.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import JSONResponse
3
+ import sqlite3
4
+ from pydantic import BaseModel
5
+ class DataType(BaseModel):
6
+ Email:str
7
+ Password:str
8
+ GetUserDataRouter=APIRouter(prefix="/Users")
9
+ @GetUserDataRouter.post("/GetUserData")
10
+ def adduser(Dat:DataType):
11
+ try:
12
+ State=False
13
+ connect=sqlite3.connect("DataBase/DataBase.bd")
14
+ cursor=connect.execute(f'''
15
+ SELECT UserId,Password FROM Users where Email='{Dat.Email}'
16
+ ''')
17
+
18
+ Data=cursor.fetchall()
19
+ if len(Data)!=0:
20
+ if Data[0][0]==None:
21
+ return {"Status":False,"Message":"Email or Password Is Incorrect "}
22
+
23
+ HasedPassword=Data[0][1]
24
+ UserId=Data[0][0]
25
+ State=Dat.Password==HasedPassword
26
+ if not State:
27
+ return {"Status":False,"Message":"Email or Password is not correct"}
28
+
29
+ cursor=connect.execute(f'''
30
+
31
+ SELECT UserName,Job,Phonenumber,Place,BDay FROM Users where UserId={UserId}
32
+ ''')
33
+ Data=cursor.fetchone()
34
+ if len(Data)!=0:
35
+
36
+ if Data[0][0]==None:
37
+ return {"Status":True,"Message":"Error Not Found"}
38
+ else:
39
+ return {"Status":True,"Data":Data}
40
+
41
+ return {"Status":False,"Message":"Error Not Found"}
42
+ except Exception as e:
43
+ return {"Status":False,"Message":e}
Logic/FUsers/GetUsersItems.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ import sqlite3
3
+ from os import listdir
4
+ from os.path import exists
5
+ from pydantic import BaseModel
6
+ class DataType(BaseModel):
7
+ Email:str
8
+ Password:str
9
+ # from jose import jwt,JWTError
10
+ UserItemGetRouter=APIRouter(prefix="/Users")
11
+ @UserItemGetRouter.post("/GetUserItem")
12
+ def adduser(Dat:DataType):
13
+ try:
14
+
15
+ State=False
16
+ connect=sqlite3.connect("DataBase/DataBase.bd")
17
+ cursor=connect.execute(f'''
18
+ SELECT UserId,Password FROM Users where Email='{Dat.Email}'
19
+ ''')
20
+
21
+ Data=cursor.fetchall()
22
+ if len(Data)!=0:
23
+ if Data[0][0]==None:
24
+ return {"Status":False,"Message":"Email or Password Is Incorrect "}
25
+
26
+ HasedPassword=Data[0][1]
27
+ UserId=Data[0][0]
28
+ State=Dat.Password==HasedPassword
29
+ if not State:
30
+ return {"Status":False,"Message":"Email or Password is not correct"}
31
+
32
+ cursor=connect.execute(f'''
33
+ SELECT UserItemName FROM UserItems where UserId={UserId}
34
+ ''')
35
+ Data=cursor.fetchall()
36
+ if len(Data)!=0:
37
+
38
+ if Data[0][0]==None:
39
+ return {"Status":True,"Data":[]}
40
+ else:
41
+ UsersItems=[]
42
+ for i in Data:
43
+ num=0
44
+ if exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{i[0]}"):
45
+ num=len(listdir(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/{i[0]}"))
46
+
47
+ UsersItems.append({"Name":i[0],"NumImages":num})
48
+ return {"Status":True,"Data":UsersItems}
49
+
50
+ return {"Status":False,"Message":[]}
51
+ except Exception as e:
52
+ return {"Status":False,"Message":e}
Logic/FaceRecognition/StoreImage.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,UploadFile,Form,File
2
+ from PIL import Image
3
+ import mediapipe as mp
4
+ from numpy import sqrt, array,abs
5
+ from io import BytesIO
6
+ from os.path import exists
7
+ from passlib.context import CryptContext
8
+ from sqlite3 import connect
9
+ from datetime import datetime
10
+ MediapipeModelPath="./Models/face_landmarker.task"
11
+
12
+ BaseOptions=mp.tasks.BaseOptions
13
+ FaceLandMarker=mp.tasks.vision.FaceLandmarker
14
+ FaceLandMarkerOptions=mp.tasks.vision.FaceLandmarkerOptions
15
+ VisionRunningMode=mp.tasks.vision.RunningMode
16
+ FaceLandMarkerResult=mp.tasks.vision.FaceLandmarkerResult
17
+ options=FaceLandMarkerOptions(base_options=BaseOptions(model_asset_path=MediapipeModelPath),running_mode=VisionRunningMode.IMAGE)
18
+ landmarker= FaceLandMarker.create_from_options(options)
19
+ # class DataType(BaseModel):
20
+ # Images:UploadFile
21
+ # Email:EmailStr
22
+ # Password:str
23
+ # Name:str
24
+ # Type:str
25
+
26
+ # def asform(Images:UploadFile=File(...),Email:str=Form(...),Password:str=Form(...),Name:str=Form(...),Type:str=Form(...))->DataType:
27
+ # return DataType(Images=Images,Email=Email,Password=Password,Name=Name,Type=Type)
28
+ UploaderRouter=APIRouter(prefix="/Uploader")
29
+
30
+ @UploaderRouter.post("/ImageUpload")
31
+ async def SpeachToTextEndPoint(Images:UploadFile=File(...),Email:str=Form(...),Password:str=Form(...),Name:str=Form(...),Type:str=Form(...)):
32
+ try:
33
+ State=False
34
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
35
+ con=connect("./DataBase/DataBase.bd")
36
+ cursor=con.execute(f'''
37
+ SELECT UserId,Password FROM Users where Email='{Email}'
38
+ ''')
39
+
40
+ Data=cursor.fetchall()
41
+ if len(Data) !=0 :
42
+ if Data[0][0]==None:
43
+ return {"Status":True,"Message":"Email or Password Is Incorrect"}
44
+ HasedPassword=Data[0][1]
45
+ UserId=Data[0][0]
46
+ State=pwd_context.verify(Password,HasedPassword)
47
+
48
+
49
+
50
+ con.close()
51
+ if not State:
52
+ return {"Status":False,"Message":"Email or Password is not correct"}
53
+
54
+
55
+ image_array=array(Image.open(BytesIO(Images.file.read())))
56
+
57
+ mp_img=mp.Image(image_format=mp.ImageFormat.SRGB,data=image_array)
58
+ result=landmarker.detect(mp_img)
59
+ State,ExtractedImage=render(results=result,FaceImage=image_array)
60
+ if exists(f"./FaceRecognition/ExtactedFaces/{UserId}/{Type}/{Name}") and State:
61
+ Image.fromarray(ExtractedImage.astype("uint8")).save(f"./FaceRecognition/ExtactedFaces/{UserId}/{Type}/{Name}/{str(datetime.now()).split('.')[-1]}-{Images.filename}","PNG")
62
+ else:
63
+ return {"Status":False,"Message":"Cant Find That Person"}
64
+
65
+ return {"Satus":True}
66
+
67
+ except Exception as e:
68
+ print(e)
69
+ return {"Satus":False}
70
+
71
+
72
+ def render(results,FaceImage):
73
+ res = results.face_landmarks[0]
74
+ x_=int(res[145].x*FaceImage.shape[1])
75
+ y_=int(res[145].y*FaceImage.shape[0])
76
+ x2_=int(res[374].x*FaceImage.shape[1])
77
+ y2_=int(res[374].y*FaceImage.shape[0])
78
+ w=sqrt((x_-x2_)**2+(y_-y2_)**2)
79
+ W=6.3
80
+ f = 840
81
+ d = (W * f) / w
82
+ if d >=100:
83
+ return False,None
84
+
85
+ x=int(res[356].x*FaceImage.shape[1])
86
+ y=int(res[152].y*FaceImage.shape[0])
87
+ x2=int(res[162].x*FaceImage.shape[1])
88
+ y2=int(res[338].y*FaceImage.shape[0])
89
+ if x<FaceImage.shape[1]-10:
90
+ x+=10
91
+ if y>FaceImage.shape[0]-10:
92
+ y+=10
93
+ if x2>10:
94
+ x2-=10
95
+ if y2>10:
96
+ y2-=10
97
+
98
+
99
+ ExtractedFace=FaceImage[abs(y2):abs(y),abs(x2):abs(x)]
100
+ return True,ExtractedFace
101
+
102
+
Logic/FaceRecognition/Trainer.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,BackgroundTasks,HTTPException
2
+ from os.path import exists
3
+ from os import listdir
4
+ import subprocess
5
+ from passlib.context import CryptContext
6
+ import sqlite3
7
+ ModelTrainer=APIRouter(prefix="/Trainer")
8
+ TrainingProcess={}
9
+
10
+ def TrainModel(UserId):
11
+ global TrainingProcess
12
+ if TrainingProcess.get(UserId,False) and TrainingProcess[UserId].poll() is None:
13
+ raise HTTPException(status_code=400,detail="Model is already training.")
14
+ TrainingProcess=subprocess.Popen(["python","./FaceRecognition/ModelTrainer.py",f"{UserId}"])
15
+
16
+
17
+
18
+ @ModelTrainer.post("/TrainFaceModel")
19
+ async def SpeachToTextEndPoint(Tasks:BackgroundTasks,Email:str,Password:str):
20
+ global TrainingProcess
21
+
22
+ try:
23
+ State=False
24
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
25
+ connect=sqlite3.connect("DataBase/DataBase.bd")
26
+ cursor=connect.execute(f'''
27
+ SELECT UserId,Password FROM Users where Email='{Email}'
28
+ ''')
29
+
30
+ Data=cursor.fetchall()
31
+ if len(Data) !=0 :
32
+ if Data[0][0]==None:
33
+ return {"Status":True,"Message":"Email or Password Is Incorrect"}
34
+ HasedPassword=Data[0][1]
35
+ UserId=Data[0][0]
36
+
37
+ State=pwd_context.verify(Password,HasedPassword)
38
+
39
+ if exists(f"./FaceRecognition/ExtactedFaces/{UserId}/Train"):
40
+ for UserName in listdir(f"./FaceRecognition/ExtactedFaces/{UserId}/Train"):
41
+ if len(listdir(f"./FaceRecognition/ExtactedFaces/{UserId}/Train/"+UserName))<2:
42
+ return {"Status":False,"Message":f"{UserName} has only {len(listdir(f'./FaceRecognition/ExtactedFaces/{UserId}/Train/'+UserName))} image and it must be 2 or more"}
43
+ if not State:
44
+ return {"Status":False,"Message":"Email or Password is not correct"}
45
+ if TrainingProcess.get(UserId,False) and TrainingProcess[UserId].poll() is None:
46
+ raise HTTPException(status_code=400,detail="Model is already training.")
47
+ Tasks.add_task(TrainModel ,args=[UserId])
48
+ return{"message":"Training Started"}
49
+ except Exception as e:
50
+ return{"Stats":False,"message":f"{e}"}
51
+
52
+ @ModelTrainer.post("/TrainFaceModelStatus")
53
+ async def SpeachToTextEndPoint(Email:str,Password:str):
54
+ global TrainingProcess
55
+ try:
56
+ State=False
57
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
58
+ connect=sqlite3.connect("DataBase/DataBase.bd")
59
+ cursor=connect.execute(f'''
60
+ SELECT UserId,Password FROM Users where Email='{Email}'
61
+ ''')
62
+ if len(cursor.fetchall())==1:
63
+ HasedPassword=cursor.fetchall()[0][1]
64
+ UserId=cursor.fetchall()[0][0]
65
+ State=pwd_context.verify(Password,HasedPassword)
66
+ if not State:
67
+ return {"Status":False,"Message":"Email or Password is not correct"}
68
+ if TrainingProcess.get(UserId,False) and TrainingProcess[UserId].poll() is None:
69
+ return{"message":"Model still Training "}
70
+ else:
71
+ return{"message":"Model Training ended"}
72
+ except Exception as e:
73
+ return{"Stats":True,"message":f"{e}"}
Logic/GetModels/FaceModel.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import FileResponse
3
+ from passlib.context import CryptContext
4
+
5
+ import sqlite3
6
+ FaceModelRouter=APIRouter(prefix="/GetModel")
7
+ @FaceModelRouter.post("/GetFaceModel")
8
+ def FaceModelEndPoint(Email:str,Password:str):
9
+ try:
10
+ State=False
11
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
12
+ connect=sqlite3.connect("DataBase/DataBase.bd")
13
+ cursor=connect.execute(f'''
14
+ SELECT Password FROM Users where Email='{Email}'
15
+ ''')
16
+ if len(cursor.fetchall())==1:
17
+ HasedPassword=cursor.fetchall()[0][0]
18
+ State=pwd_context.verify(Password,HasedPassword)
19
+ if not State:
20
+ return {"Status":False,"Message":"Email or Password is not correct"}
21
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
22
+ Password=pwd_context.hash(Password)
23
+ connect=sqlite3.connect("DataBase/DataBase.bd")
24
+ cursor=connect.execute(f'''
25
+ SELECT UserId FROM Users where Email='{Email}'
26
+ ''')
27
+ if len(cursor.fetchall())==0:
28
+ return {"Status":False,"Message":"somthing went wrong"}
29
+ UserId=cursor.fetchone()["UserId"]
30
+ return FileResponse(f"./ExtactedFaces/FaceModel/{UserId}/FinalFaceModel.tflite")
31
+
32
+ except Exception as e:
33
+ return {"Status":False,"Message":e}
Logic/GetModels/IndoorModel.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import FileResponse
3
+ from passlib.context import CryptContext
4
+ import sqlite3
5
+ IndoorModelRouter=APIRouter(prefix="/GetModel")
6
+ @IndoorModelRouter.post("/GetIndoorModel")
7
+ def FaceModelEndPoint(Email:str,Password:str):
8
+ try:
9
+
10
+ State=False
11
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
12
+ connect=sqlite3.connect("DataBase/DataBase.bd")
13
+ cursor=connect.execute(f'''
14
+ SELECT Password FROM Users where Email='{Email}'
15
+ ''')
16
+ if len(cursor.fetchall())==1:
17
+ HasedPassword=cursor.fetchall()[0][0]
18
+ State=pwd_context.verify(Password,HasedPassword)
19
+ if not State:
20
+ return {"Status":False,"Message":"Email or Password is not correct"}
21
+
22
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
23
+ Password=pwd_context.hash(Password)
24
+ connect=sqlite3.connect("DataBase/DataBase.bd")
25
+ cursor=connect.execute(f'''
26
+ SELECT UserId FROM Users where Email='{Email}'
27
+ ''')
28
+ if len(cursor.fetchall())==0:
29
+ return {"Status":False,"Message":"somthing went wrong"}
30
+ UserId=cursor.fetchone()["UserId"]
31
+ return FileResponse(f"./IndoorLocalization/IndoorModels/{UserId}/FinalHistoryModel.tflite")
32
+
33
+ except Exception as e:
34
+ return {"Status":False,"Message":e}
Logic/IndoorLocalization/StoreNewLabel.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ import pandas as read_csv
3
+ from sqlite3 import connect
4
+ from os.path import isfile
5
+ from pydantic import BaseModel
6
+ class DataType(BaseModel):
7
+ label:str
8
+ Email:str
9
+ Password:str
10
+ IndoorLabel=APIRouter(prefix="/Uploader")
11
+ @IndoorLabel.post("/AddWiFiLAbel")
12
+ async def FunctionName(Data:DataType):
13
+
14
+ try:
15
+
16
+
17
+ con=connect("DataBase/DataBase.bd")
18
+ cursor=con.execute(f'''
19
+ SELECT UserId,Password FROM Users where Email='{Data.Email}'
20
+ ''')
21
+ if len(cursor.fetchall())==1:
22
+
23
+ HasedPassword=cursor.fetchall()[0][1]
24
+ UserId=cursor.fetchall()[0][0]
25
+ State=Data.Password==HasedPassword
26
+ con.close()
27
+ if State:
28
+ if not isfile(f"./IndoorLocalization/Data/{UserId}/Data.csv"):
29
+ return {"Status":False,"message":"Cant Find DataSet"}
30
+ Labels=map(lambda x:int(x),Data.label.split(sep=","))
31
+ DATA=read_csv(f"./IndoorLocalization/Data/{UserId}/Data.csv")
32
+ DATA.loc[DATA.shape[0]]=Labels
33
+ DATA.to_csv(f"./IndoorLocalization/Data/{UserId}/Data.csv",index=False)
34
+ return {"Status":True,"message":"Store Done "}
35
+
36
+ else:
37
+ return {"Status":False,"Message":"Email or Password is not correct"}
38
+
39
+
40
+
41
+ except Exception as e:
42
+
43
+ return {"Status":False,"message":e}
44
+
Logic/IndoorLocalization/Trainer.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,BackgroundTasks,HTTPException
2
+ import sqlite3
3
+ from passlib.context import CryptContext
4
+ import subprocess
5
+ from pydantic import BaseModel
6
+ ModelIndoorTrainer=APIRouter(prefix="/Trainer")
7
+ TrainingProcess2={}
8
+
9
+ def TrainModel(UserId):
10
+ global TrainingProcess2
11
+ if TrainingProcess2.get(UserId,False) and TrainingProcess2.get(UserId).poll():
12
+ raise HTTPException(status_code=400,detail="Model is already training.")
13
+ TrainingProcess2[UserId]=subprocess.Popen(["python","./IndoorLocalization/IndoorlocalizationTrainer.py",f"{UserId}"])
14
+ TrainingProcess2[UserId]=None
15
+
16
+
17
+ class DataType(BaseModel):
18
+ Email:str
19
+ Password:str
20
+ @ModelIndoorTrainer.post("/TrainIndoorModel")
21
+ async def SpeachToTextEndPoint(Tasks:BackgroundTasks,Data:DataType):
22
+ global TrainingProcess2
23
+ try:
24
+
25
+ connect=sqlite3.connect("DataBase/DataBase.bd")
26
+ cursor=connect.execute(f'''
27
+ SELECT UserId,Password FROM Users where Email='{Data.Email}'
28
+ ''')
29
+ if len(cursor.fetchall())==1:
30
+ HasedPassword=cursor.fetchall()[0][1]
31
+ UserId=cursor.fetchall()[0][0]
32
+ State=Data.Password==HasedPassword
33
+ if State:
34
+ if TrainingProcess2.get(UserId,False) and TrainingProcess2.get(UserId).poll() is None:
35
+ raise HTTPException(status_code=400,detail="Model is already training.")
36
+ Tasks.add_task(TrainModel,args=[UserId])
37
+ return{"message":"Training Started"}
38
+
39
+
40
+ else:
41
+ return {"Status":False,"Message":"Email or Password is not correct"}
42
+ except Exception as e:
43
+ return {"Status":False,"Message":f"{e}"}
44
+
45
+
46
+
47
+
48
+ @ModelIndoorTrainer.post("/TrainIndoorModelStatus")
49
+ async def SpeachToTextEndPoint(Data:DataType):
50
+ global TrainingProcess2
51
+ try:
52
+
53
+
54
+ connect=sqlite3.connect("DataBase/DataBase.bd")
55
+ cursor=connect.execute(f'''
56
+ SELECT UserId, Password FROM Users where Email='{Data.Email}'
57
+ ''')
58
+ if len(cursor.fetchall())==1:
59
+ HasedPassword=cursor.fetchall()[0][1]
60
+ UserId=cursor.fetchall()[0][0]
61
+ State=Data.Password==HasedPassword
62
+ if State:
63
+ if TrainingProcess2.get(UserId,False) and TrainingProcess2.get(UserId).poll() is None:
64
+ return{"message":"Model still Training "}
65
+ else:
66
+ return{"message":"Model Training ended"}
67
+
68
+
69
+ else:
70
+ return {"Status":False,"Message":"Email or Password is not correct"}
71
+ except Exception as e:
72
+ return {"Status":False,"Message":f"{e}"}
73
+
Logic/IndoorLocalization/UserDataSetUploader.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,UploadFile,Form,File
2
+ from sqlite3 import connect
3
+
4
+ IndoorDataUploader=APIRouter(prefix="/Uploader")
5
+ @IndoorDataUploader.post("/UploadeWiFiData")
6
+ async def FunctionName(Dataset:UploadFile=File(...),Email:str=Form(...),Password:str=Form(...)):
7
+
8
+ try:
9
+ con=connect("DataBase/DataBase.bd")
10
+ cursor=con.execute(f'''
11
+ SELECT UserId,Password FROM Users where Email='{Email}'
12
+ ''')
13
+ Data=cursor.fetchall()
14
+ if len(Data) !=0 :
15
+ if Data[0][0]==None:
16
+ return {"Status":False,"Message":"Email or Password Is Incorrect "}
17
+ HasedPassword=Data[0][1]
18
+ UserId=Data[0][0]
19
+ State=Password==HasedPassword
20
+
21
+ con.close()
22
+ if State:
23
+ with open(f"./IndoorLocalization/Data/{UserId}/Data.csv","wb") as File:
24
+ File.write(Dataset.file.read())
25
+
26
+ return {"Status":True,"Message":"File Added Correctly"}
27
+
28
+ else:
29
+ return {"Status":False,"Message":"Email or Password is not correct"}
30
+
31
+
32
+
33
+ except Exception as e:
34
+
35
+ return {"Status":False,"message":e}
36
+
Logic/Locations/GetDays.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import JSONResponse
3
+ import sqlite3
4
+ from passlib.context import CryptContext
5
+ from pydantic import BaseModel
6
+ UserGetTrackingDateRouter=APIRouter(prefix="/Location")
7
+ class Data(BaseModel):
8
+ Email:str
9
+ Password:str
10
+
11
+ @UserGetTrackingDateRouter.post("/GetTrackingDate")
12
+ def adduser(Dat:Data):
13
+ try:
14
+ Email= Dat.Email
15
+ Password=Dat.Password
16
+ connect=sqlite3.connect("DataBase/DataBase.bd")
17
+ State=False
18
+
19
+
20
+
21
+ cursor=connect.execute(f'''
22
+ SELECT UserId,Password FROM Users where Email='{Email}'
23
+ ''')
24
+ Data=cursor.fetchall()
25
+ if len(Data) !=0 :
26
+ if Data[0][0]==None:
27
+ return {"Status":True,"Message":"User Is Not Defined Before"}
28
+ HasedPassword=Data[0][1]
29
+ UserId=Data[0][0]
30
+ State=Password==HasedPassword
31
+ if State:
32
+ cursor=connect.execute(f'''
33
+ SELECT DISTINCT Day FROM TrackeringPoints WHERE UserId={UserId}
34
+ ''')
35
+
36
+ DataCollected=cursor.fetchall()
37
+ if len(DataCollected)==0:
38
+ DataCollected=[["Nodays Found"]]
39
+ connect.close()
40
+
41
+ return {
42
+ "Status":True,
43
+ "Data":DataCollected,
44
+ }
45
+
46
+ else:
47
+ return {"State":False}
48
+
49
+ except Exception as e :
50
+ return {"Status":False,"Message":e}
51
+
Logic/Locations/GetMapOfuser.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ import sqlite3
3
+ from numpy import array,mean
4
+ from pydantic import BaseModel
5
+ UserGetLocationRouter=APIRouter(prefix="/Location")
6
+ class DataType(BaseModel):
7
+ Email:str
8
+ Password:str
9
+ Day:str
10
+
11
+ @UserGetLocationRouter.post("/GetMapLocations")
12
+ def adduser(Data:DataType):
13
+ try:
14
+ Email=Data.Email
15
+ Password=Data.Password
16
+ Day=Data.Day
17
+ State=False
18
+
19
+ # pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
20
+
21
+
22
+ connect=sqlite3.connect("DataBase/DataBase.bd")
23
+ cursor=connect.execute(f'''
24
+ SELECT UserId,Password FROM Users where Email='{Email}'
25
+ ''')
26
+ Data=cursor.fetchall()
27
+ if len(Data) !=0 :
28
+ if Data[0][0]==None:
29
+ return {"Status":False,"Message":"User Is Not Defined Before"}
30
+ HasedPassword=Data[0][1]
31
+ UserId=Data[0][0]
32
+ State=Password==HasedPassword
33
+ if State:
34
+ cursor=connect.execute(f'''
35
+ SELECT Longtude , Lattitude,Houre FROM TrackeringPoints WHERE Day='{Day}' and UserId={UserId}
36
+ ''')
37
+ DataCollected=cursor.fetchall()
38
+ # cursor2=connect.execute(f'''
39
+ # SELECT AVG(Longtude) , AVG(Lattitude) TrackeringPoints WHERE Day='{Day}' and UserId={UserId}
40
+ # ''')
41
+
42
+
43
+ # PositionsMean=cursor2.fetchall()
44
+ connect.close()
45
+ if len(DataCollected)==0:
46
+ return {
47
+ "Status":True,
48
+ "Data":{
49
+
50
+ "PositionData":[],
51
+ "Time":[],
52
+ "Mean":[12.3,50]
53
+
54
+ }
55
+ }
56
+ PositionData=[ [ item[0],item[1]]for item in DataCollected]
57
+ PositionsMean=mean(array(PositionData),axis=0)
58
+ Houre=[ item[2] for item in DataCollected]
59
+
60
+ return {
61
+ "Status":True,
62
+ "Data":{
63
+
64
+ "PositionData":PositionData,
65
+ "Time":Houre,
66
+ "Mean":PositionsMean
67
+
68
+ }
69
+ }
70
+ else:
71
+ return {"State":False}
72
+ except Exception as e :
73
+ return {"Status":False,"Message":e}
74
+
Logic/Locations/SetLocationForUser.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ import sqlite3
3
+ from passlib.context import CryptContext
4
+ from pydantic import BaseModel
5
+ class DataType(BaseModel):
6
+ Email:str
7
+ Password:str
8
+ Longtude:str
9
+ Lattitude:str
10
+ Day:str
11
+ Houre:str
12
+ UserAddLocationRouter=APIRouter(prefix="/Location")
13
+ @UserAddLocationRouter.post("/AddLocation")
14
+ def adduser(Data:DataType):
15
+ try:
16
+
17
+ State=False
18
+
19
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
20
+
21
+
22
+ connect=sqlite3.connect("DataBase/DataBase.bd")
23
+ cursor=connect.execute(f'''
24
+ SELECT UserId,Password FROM Users where Email='{Data.Email}'
25
+ ''')
26
+ Data=cursor.fetchall()
27
+ if len(Data) !=0 :
28
+ if Data[0][0]==None:
29
+ return {"Status":True,"Message":"User Is Not Defined Before"}
30
+ HasedPassword=Data[0][1]
31
+ UserId=Data[0][0]
32
+ State=Data.Password==HasedPassword
33
+ if State:
34
+ connect.execute(f'''
35
+ INSERT INTO TrackeringPoints (UserId,Longtude ,Lattitude,Day,Houre) VALUES ({UserId},{float(Data.Longtude)},{float(Data.Lattitude)},'{Data.Day}','{Data.Houre}')
36
+ ''')
37
+ connect.commit()
38
+ connect.close()
39
+ return {"State":True}
40
+ else:
41
+ return {"State":False}
42
+ except Exception as e :
43
+ return {"Status":False,"Message":e}
44
+
Logic/Login.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,Form
2
+ from passlib.context import CryptContext
3
+ from pydantic import BaseModel
4
+ import sqlite3
5
+ class DataType(BaseModel):
6
+ AdminEmail:str=Form(...)
7
+ AdminPassword:str=Form(...)
8
+ LogInRouter=APIRouter()
9
+ @LogInRouter.post("/Login")
10
+ def adduser(AdminEmail:str=Form(...),AdminPassword:str=Form(...),Type:str=Form(...)):
11
+ try:
12
+ # #mohammed*123#
13
+ pwd_context=CryptContext(schemes=["bcrypt"],deprecated="auto")
14
+ if Type=="Admin":
15
+
16
+ AdminPasswordq="$2b$12$33H14GFBvtomzLrEaM6Tqu7Jr621eHlXL9TVtdPU6YCljxc4eug2a"
17
+ if AdminEmail =="[email protected]":
18
+ if pwd_context.verify( AdminPassword,AdminPasswordq):
19
+ return {"Status":True,
20
+ "Data":{"AdminEmail":"[email protected]",
21
+ "AdminPassword":AdminPasswordq
22
+ }}
23
+ else:
24
+ return {"Status":False,"Message":" Admin Email or Password is not correct "}
25
+ else:
26
+ return {"Status":False,"Message":" Admin Email or Password is not correct "}
27
+ else:
28
+ connect=sqlite3.connect("DataBase/DataBase.bd")
29
+ State=False
30
+
31
+ cursor=connect.execute(f'''
32
+ SELECT UserId,Password FROM Users where Email='{AdminEmail}'
33
+ ''')
34
+ Data=cursor.fetchall()
35
+ if len(Data) !=0 :
36
+ if Data[0][0]==None:
37
+ return {"Status":False,"Message":"User Is Not Defined Before"}
38
+ HasedPassword=Data[0][1]
39
+ UserId=Data[0][0]
40
+ State=pwd_context.verify( AdminPassword,HasedPassword)
41
+ if State:
42
+ return {"Status":True,
43
+ "Data":{"Email":AdminEmail,
44
+ "Password":HasedPassword,
45
+ "UserId":UserId
46
+ }}
47
+ except Exception as e :
48
+ return {"Status":False,"Message":e}
Logic/SpeachToText.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter,UploadFile
2
+ from io import BytesIO
3
+ import speech_recognition as sr
4
+ from scipy.io import wavfile
5
+ from os import environ
6
+ Recognizer=sr.Recognizer()
7
+ SpeachRouter=APIRouter()
8
+ @SpeachRouter.post("/SpeachTotext")
9
+ def SpeachToTextEndPoint(Audio:UploadFile):
10
+ try:
11
+ with sr.AudioFile(BytesIO(Audio.file.read())) as File:
12
+
13
+ audio=Recognizer.listen(File)
14
+ environ["GOOGLE_APPLICATION_CREDENTIALS"]="smms"
15
+ Text:str=Recognizer.recognize_google(audio,language="en-US")
16
+
17
+ if ("on" in Text and "light" in Text) or ("off" not in Text and "light" in Text):
18
+ return {"Status":True,"Message":"l"} # l ::LightOn
19
+ elif "light" in Text:
20
+ return {"Status":True,"Message":"o"} # o ::LightOff
21
+
22
+
23
+ except LookupError as e:
24
+ return {"Status":False,"Message":e}
Models/face_landmarker.task ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff
3
+ size 3758596
Router/AppRouter.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import HTMLResponse
3
+
4
+ from Logic.SpeachToText import SpeachRouter
5
+ from Logic.FaceRecognition.StoreImage import UploaderRouter
6
+ from Logic.FaceRecognition.Trainer import ModelTrainer
7
+ from Logic.IndoorLocalization.StoreNewLabel import IndoorLabel
8
+ from Logic.FUsers.AddUser import UserAddRouter
9
+ from Logic.FUsers.DeleteUser import DeleteUserRouter
10
+ from Logic.GetModels.FaceModel import FaceModelRouter
11
+ from Logic.GetModels.IndoorModel import IndoorModelRouter
12
+ from Logic.IndoorLocalization.Trainer import ModelIndoorTrainer
13
+ from Logic.FUsers.AddUserItem import UserItemAddRouter
14
+ from Logic.FUsers.GetUsersItems import UserItemGetRouter
15
+ from Logic.FUsers.DeleteUserItem import UserItemDeleteRouter
16
+ from Logic.IndoorLocalization.UserDataSetUploader import IndoorDataUploader
17
+ from Logic.Locations.GetMapOfuser import UserGetLocationRouter
18
+ from Logic.Locations.SetLocationForUser import UserAddLocationRouter
19
+ from Logic.Locations.GetDays import UserGetTrackingDateRouter
20
+ from Logic.Login import LogInRouter
21
+ from Logic.FUsers.GetAllUsers import GetUserRouter
22
+ from Logic.FUsers.GetUserData import GetUserDataRouter
23
+ MainRouter=APIRouter()
24
+ MainRouter.include_router(LogInRouter)
25
+ MainRouter.include_router(SpeachRouter)
26
+ MainRouter.include_router(UploaderRouter)
27
+ MainRouter.include_router(ModelTrainer)
28
+ MainRouter.include_router(IndoorLabel)
29
+ MainRouter.include_router(UserAddRouter)
30
+ MainRouter.include_router(GetUserRouter)
31
+ MainRouter.include_router(DeleteUserRouter)
32
+ MainRouter.include_router(FaceModelRouter)
33
+ MainRouter.include_router(IndoorModelRouter)
34
+ MainRouter.include_router(ModelIndoorTrainer)
35
+ MainRouter.include_router(UserItemAddRouter)
36
+ MainRouter.include_router(UserItemDeleteRouter)
37
+ MainRouter.include_router(UserItemGetRouter)
38
+ MainRouter.include_router(IndoorDataUploader)
39
+ MainRouter.include_router(UserAddLocationRouter)
40
+ MainRouter.include_router(UserGetLocationRouter)
41
+ MainRouter.include_router(UserGetTrackingDateRouter)
42
+ MainRouter.include_router(GetUserDataRouter)
43
+ @MainRouter.get("/",response_class=HTMLResponse)
44
+ def home():
45
+ return '''
46
+ <html>
47
+ <head>
48
+ <title>
49
+ Face Recognition
50
+ </title>
51
+ <style>
52
+ *{
53
+ padding:0px;
54
+ margin:0px;
55
+ }
56
+ h1:hover{
57
+ background:#00f;
58
+ color:#fff;
59
+ cursor:pointer;
60
+ }
61
+ </style>
62
+ </head>
63
+ <body>
64
+ <div style="display:flex;align-items:center; justify-content: center;height: 100vh;color: #b3a1a1;">
65
+ <h1 style="border: 1px solid #00f;padding: 30px;border-radius: 20px;">Face Recognition App By Aboellil</h1>
66
+ </div>
67
+ <body>
68
+ </html>
69
+
70
+
71
+
72
+ '''
73
+
Router/__pycache__/AppRouter.cpython-311.pyc ADDED
Binary file (3.8 kB). View file
 
main.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI,Request
2
+ from fastapi.staticfiles import StaticFiles
3
+ from fastapi.responses import JSONResponse
4
+ from Router.AppRouter import MainRouter
5
+ from sqlite3 import connect
6
+ from os.path import exists
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from passlib.context import CryptContext
9
+ app=FastAPI()
10
+ try:
11
+
12
+ conn=connect("DataBase/DataBase.bd")
13
+
14
+ conn.execute("PRAGMA foreign_keys=ON")
15
+
16
+ conn.execute('''
17
+ create table if not exists Users (UserId int primary key
18
+ ,Email text not null ,
19
+ UserName text not null,
20
+ Job text not null,
21
+ Phonenumber text not null,
22
+ Place text not null,
23
+ BDay text not null,
24
+ Password Text Not Null);
25
+ ''')
26
+
27
+
28
+ conn.execute('''
29
+ create table if not exists TrackeringPoints
30
+ (UserId int
31
+ ,Longtude REAL not null
32
+ ,Lattitude REAL Not Null
33
+ ,Day text not null
34
+ ,Houre text not null
35
+ , foreign key (UserId) references Users(UserId))
36
+ ''')
37
+ conn.execute('''
38
+ create table if not exists UserModelVersion (UserId int
39
+ ,FaceModel INT not null
40
+ ,IndoorModel INT Not Null,
41
+ foreign key (UserId) references Users(UserId))
42
+ ''')
43
+ conn.execute('''
44
+ create table if not exists UserItems (
45
+ UserId int ,
46
+ UserItemName TEXT not null,
47
+ foreign key (UserId) references Users(UserId))
48
+ ''')
49
+
50
+ conn.close()
51
+
52
+
53
+ except Exception as e:
54
+ print(e)
55
+
56
+ app.mount("/static",StaticFiles(directory="./static"),name="static")
57
+
58
+ app.add_middleware(CORSMiddleware,
59
+ allow_origins=["*"],
60
+ allow_credentials=True,
61
+ allow_methods=["*"],
62
+ allow_headers=["admin-email","admin-password","content-type"],
63
+ )
64
+
65
+
66
+
67
+
68
+ app.include_router(MainRouter)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ numpy
3
+ uvicorn
4
+ python-multipart
5
+ tensorflow
6
+ passlib
7
+ sqlite3
8
+ os
9
+ sklearn
10
+ keras
11
+ pandas
12
+ scipy
13
+ speech_recognition