//		static AfisEngine Afis = new AfisEngine();

//		// Inherit from Fingerprint in order to add Filename field
//		[Serializable]
//		class MyFingerprint : Fingerprint
//		{
//			public string Filename;
//		}
//
//		// Inherit from Person in order to add Name field
//		[Serializable]
//		class MyPerson : Person
//		{
//			public string Name;
//		}

		// Take fingerprint image file and create Person object from the image
		public static MyPerson Enroll(string filename, string name, AfisEngine Afis)
		{
			Console.WriteLine("Enrolling {0}...", name);

			// Initialize empty fingerprint object and set properties
			MyFingerprint fp = new MyFingerprint();
			fp.Filename = filename;
			// Load image from the file
			Console.WriteLine(" Loading image from {0}...", filename);
			//            BitmapImage image = new BitmapImage(new Uri(filename, UriKind.RelativeOrAbsolute));
			Bitmap image = (Bitmap) Image.FromFile(@filename, true);
			//			Bitmap image = Bitmap.FromFile(@filename, true);

			fp.AsBitmap = image;
			// Above update of fp.AsBitmapSource initialized also raw image in fp.Image
			// Check raw image dimensions, Y axis is first, X axis is second
			Console.WriteLine(" Image size = {0} x {1} (width x height)", fp.Image.GetLength(1), fp.Image.GetLength(0));

			// Initialize empty person object and set its properties
			MyPerson person = new MyPerson();
			person.Name = name;
			person.Uuid = name;
			// Add fingerprint to the person
			person.Fingerprints.Add(fp);

			// Execute extraction in order to initialize fp.Template
			Console.WriteLine(" Extracting template...");
			Afis.Extract(person);
			// Check template size
			Console.WriteLine(" Template size = {0} bytes", fp.Template.Length);

			return person;
		}
Example #2
0
//		static AfisEngine Afis = new AfisEngine();

//		// Inherit from Fingerprint in order to add Filename field
//		[Serializable]
//		class MyFingerprint : Fingerprint
//		{
//			public string Filename;
//		}
//
//		// Inherit from Person in order to add Name field
//		[Serializable]
//		class MyPerson : Person
//		{
//			public string Name;
//		}

        // Take fingerprint image file and create Person object from the image
        public static MyPerson Enroll(string filename, string name, AfisEngine Afis)
        {
            Console.WriteLine("Enrolling {0}...", name);

            // Initialize empty fingerprint object and set properties
            MyFingerprint fp = new MyFingerprint();

            fp.Filename = filename;
            // Load image from the file
            Console.WriteLine(" Loading image from {0}...", filename);
            //            BitmapImage image = new BitmapImage(new Uri(filename, UriKind.RelativeOrAbsolute));
            Bitmap image = (Bitmap)Image.FromFile(@filename, true);

            //			Bitmap image = Bitmap.FromFile(@filename, true);

            fp.AsBitmap = image;
            // Above update of fp.AsBitmapSource initialized also raw image in fp.Image
            // Check raw image dimensions, Y axis is first, X axis is second
            Console.WriteLine(" Image size = {0} x {1} (width x height)", fp.Image.GetLength(1), fp.Image.GetLength(0));

            // Initialize empty person object and set its properties
            MyPerson person = new MyPerson();

            person.Name = name;
            person.Uuid = name;
            // Add fingerprint to the person
            person.Fingerprints.Add(fp);

            // Execute extraction in order to initialize fp.Template
            Console.WriteLine(" Extracting template...");
            Afis.Extract(person);
            // Check template size
            Console.WriteLine(" Template size = {0} bytes", fp.Template.Length);

            return(person);
        }
Example #3
0
        //public object Get(Files request)
        //{
        //    var targetFile = GetAndValidateExistingPath(request);

        //    var isDirectory = Directory.Exists(targetFile.FullName);

        //    if (!isDirectory && request.ForDownload)
        //        return new HttpResult(targetFile, asAttachment: true);

        //    var response = isDirectory
        //        ? new FilesResponse { Directory = GetFolderResult(targetFile.FullName) }
        //        : new FilesResponse { File = GetFileResult(targetFile) };

        //    return response;
        //}

        //		[AddHeader(ContentType = "text/json")]
        public object Post(Files request)
        {
            //var container = ServiceStackHost.Instance.Container;

            //			var response = new MyPerson { };
            var response  = "";
            var message   = "";
            var uuid      = "";
            var token     = "";
            var targetDir = GetPath(request);

            var isExistingFile = targetDir.Exists &&
                                 (targetDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory;

            if (isExistingFile)
            {
                throw new NotSupportedException(
                          "POST only supports uploading new files. Use PUT to replace contents of an existing file");
            }

            if (!Directory.Exists(targetDir.FullName))
            {
                Directory.CreateDirectory(targetDir.FullName);
            }

            if (base.Request.Files.Length == 0)
            {
                //				message = "No files uploaded.";
            }

            foreach (var key in base.Request.FormData.AllKeys)
            {
                foreach (var val in base.Request.FormData.GetValues(key))
                {
                    if (key == "uuid")
                    {
                        uuid = val;
                        Console.WriteLine(string.Format("{0}: {1}", key, val) + " uuid set to: " + uuid);
                    }
                    else if (key == "key")
                    {
                        token = val;
                        Console.WriteLine(string.Format("{0}: {1}", key, val) + " token set to: " + token);
                    }
                }
            }

            Response jsonResponse = new Response();

            if (token == "noel.honeybee.galvanic")
            {
                foreach (var uploadedFile in base.Request.Files)
                {
                    var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName) + ".png";
                    //					if (uploadedFile.StartsWith("verify") {
                    //					}
                    uploadedFile.SaveTo(newFilePath);

                    // Enroll visitor with unknown identity
                    Guid g;
                    // Create and display the value of two GUIDs.
                    g = Guid.NewGuid();
                    DateTime date1 = DateTime.Now;
                    Console.WriteLine("Starting Enroll:  " + date1);
                    MyPerson probe = SourceAfisIdentify.Enroll(newFilePath, g.ToString(), Afis);
                    // Look up the probe using Threshold = 10
                    Afis.Threshold = 10;
                    DateTime date2 = DateTime.Now;
                    var      list  = FingerprintDatabase.people;
                    //Console.WriteLine("Identifying {0} in Database of {1} persons...", probe.Name, list.Count + " at " + date2);
                    Console.WriteLine("{0} : Identifying {1} in Database of {2} persons...", date2, probe.Name, list.Count);

                    MyPerson match = Afis.Identify(probe, list).FirstOrDefault() as MyPerson;

                    DateTime date3         = DateTime.Now;
                    var      diffInSeconds = (date3 - date2).TotalSeconds;
                    Console.WriteLine("Enroll time:  " + diffInSeconds + " seconds");
                    diffInSeconds = (date2 - date1).TotalSeconds;
                    Console.WriteLine("Total enroll + match time:  " + diffInSeconds + " seconds");


                    // Null result means that there is no candidate with similarity score above threshold
                    if (match == null)
                    {
                        message = "NoMatch";
                        jsonResponse.StatusCode = 4;
                        jsonResponse.Error      = message;
                        jsonResponse.UID        = g.ToString();
                        Console.WriteLine(message);
                        //Database.Add (probe);
                        FingerprintDatabase.AddData(probe);
                        String url = "http://localhost:5984/prints/" + g.ToString();
                        //					String data = "{_id: " + "\"" + g.ToString ()  + "\"" + ", fileName:" + "\""  + uploadedFile.FileName + "\""  + "}";
                        var person = new MyPerson();
                        //					person.Filename = uploadedFile.FileName;
                        person.Uuid = g.ToString();
                        List <Fingerprint>       probleFingerprints = probe.Fingerprints;
                        List <SimpleFingerprint> fingerprints       = new List <SimpleFingerprint>();

                        foreach (var print in probleFingerprints)
                        {
                            byte[] template = print.Template;
                            // Convert the binary input into Base64 UUEncoded output.
                            string base64String = null;
                            try
                            {
                                base64String = System.Convert.ToBase64String(template, 0, template.Length);
                            }
                            catch (System.ArgumentNullException)
                            {
                                System.Console.WriteLine("Binary data array is null.");
                            }

                            SimpleFingerprint fprint = new SimpleFingerprint();
                            fprint.Base64Template = base64String;
                            fprint.Filename       = uploadedFile.FileName;
                            DateTime dateUploaded = DateTime.Now;
                            string   isoJson      = JsonConvert.SerializeObject(dateUploaded, Formatting.None, new IsoDateTimeConverter()
                            {
                                DateTimeFormat = "yyyy-MM-dd hh:mm:ss"
                            });
                            fprint.DateUploaded = isoJson;
                            //fingerprints.Add (fprint);
                            person.simpleFingerprint = fprint;
                        }

                        person.SimpleFingerprints = fingerprints;

                        var json = NServiceKit.Text.JsonSerializer.SerializeToString(person);
                        Console.WriteLine(json);
                        WebClient client = new WebClient();
                        try
                        {
                            client.UploadString(url, "PUT", json);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                        string jsonString = JsonConvert.SerializeObject(jsonResponse);
                        response = jsonString;
                    }
                    else
                    {
                        // Print out any non-null result
                        Console.WriteLine("Probe {0} matches registered person {1}", probe.Uuid, match.Uuid);

                        // Compute similarity score
                        DateTime date4 = DateTime.Now;
                        float    score = Afis.Verify(probe, match);
                        Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Uuid, match.Uuid, score);
                        DateTime date5 = DateTime.Now;
                        diffInSeconds = (date5 - date4).TotalSeconds;
                        Console.WriteLine("Verify time:  " + diffInSeconds + " seconds");
                        message = "Match: " + probe.Name + " matches " + match.Name + " Score: " + score;

                        jsonResponse.StatusCode = 1;
                        jsonResponse.Error      = null;
                        jsonResponse.UID        = match.Uuid;
                        jsonResponse.Threshold  = score;

                        string jsonString = JsonConvert.SerializeObject(jsonResponse);
                        response = jsonString;
                    }
                }
            }
            else
            {
                jsonResponse.Error = "Auth error.";
                string jsonString = JsonConvert.SerializeObject(jsonResponse);
                response = jsonString;
            }
            return(response);
        }
 public void AddData(MyPerson person)
 {
     lock (people) people.Add(person);
 }
Example #5
0
        //public object Get(Files request)
        //{
        //    var targetFile = GetAndValidateExistingPath(request);

        //    var isDirectory = Directory.Exists(targetFile.FullName);

        //    if (!isDirectory && request.ForDownload)
        //        return new HttpResult(targetFile, asAttachment: true);

        //    var response = isDirectory
        //        ? new FilesResponse { Directory = GetFolderResult(targetFile.FullName) }
        //        : new FilesResponse { File = GetFileResult(targetFile) };

        //    return response;
        //}

		//		[AddHeader(ContentType = "text/json")]
		public object Post(Files request)
		{
			//var container = ServiceStackHost.Instance.Container;

			//			var response = new MyPerson { };
			var response = "";
			var message = "";
			var uuid = "";
			var token = "";
			var targetDir = GetPath(request);

			var isExistingFile = targetDir.Exists
										  && (targetDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory;

			if (isExistingFile)
				throw new NotSupportedException(
					"POST only supports uploading new files. Use PUT to replace contents of an existing file");

			if (!Directory.Exists(targetDir.FullName))
				Directory.CreateDirectory(targetDir.FullName);

			if (base.Request.Files.Length == 0)
			{
				//				message = "No files uploaded.";
			}

			foreach (var key in base.Request.FormData.AllKeys)
			{
				foreach (var val in base.Request.FormData.GetValues(key))
				{
					if (key == "uuid")
					{
						uuid = val;
						Console.WriteLine(string.Format("{0}: {1}", key, val) + " uuid set to: " + uuid);
					}
					else if (key == "key")
					{
						token = val;
						Console.WriteLine(string.Format("{0}: {1}", key, val) + " token set to: " + token);
					}
				}
			}

			Response jsonResponse = new Response();

			if (token == "noel.honeybee.galvanic")
			{
				foreach (var uploadedFile in base.Request.Files)
				{
					var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName) + ".png";
					//					if (uploadedFile.StartsWith("verify") {
					//					}
					uploadedFile.SaveTo(newFilePath);

					// Enroll visitor with unknown identity
					Guid g;
					// Create and display the value of two GUIDs.
					g = Guid.NewGuid();
					DateTime date1 = DateTime.Now;
					Console.WriteLine("Starting Enroll:  " + date1);
					MyPerson probe = SourceAfisIdentify.Enroll(newFilePath, g.ToString(), Afis);
					// Look up the probe using Threshold = 10
					Afis.Threshold = 10;
					DateTime date2 = DateTime.Now;
					var list = FingerprintDatabase.people;
					//Console.WriteLine("Identifying {0} in Database of {1} persons...", probe.Name, list.Count + " at " + date2);
					Console.WriteLine("{0} : Identifying {1} in Database of {2} persons...", date2, probe.Name, list.Count);

					MyPerson match = Afis.Identify(probe, list).FirstOrDefault() as MyPerson;

					DateTime date3 = DateTime.Now;
					var diffInSeconds = (date3 - date2).TotalSeconds;
					Console.WriteLine("Enroll time:  " + diffInSeconds + " seconds");
					diffInSeconds = (date2 - date1).TotalSeconds;
					Console.WriteLine("Total enroll + match time:  " + diffInSeconds + " seconds");


					// Null result means that there is no candidate with similarity score above threshold
					if (match == null)
					{
						message = "NoMatch";
						jsonResponse.StatusCode = 4;
						jsonResponse.Error = message;
						jsonResponse.UID = g.ToString();
						Console.WriteLine(message);
						//Database.Add (probe);
						FingerprintDatabase.AddData(probe);
						String url = "http://localhost:5984/prints/" + g.ToString();
						//					String data = "{_id: " + "\"" + g.ToString ()  + "\"" + ", fileName:" + "\""  + uploadedFile.FileName + "\""  + "}";
						var person = new MyPerson();
						//					person.Filename = uploadedFile.FileName;
						person.Uuid = g.ToString();
						List<Fingerprint> probleFingerprints = probe.Fingerprints;
						List<SimpleFingerprint> fingerprints = new List<SimpleFingerprint>();

						foreach (var print in probleFingerprints)
						{
							byte[] template = print.Template;
							// Convert the binary input into Base64 UUEncoded output. 
							string base64String = null;
							try
							{
								base64String = System.Convert.ToBase64String(template, 0, template.Length);
							}
							catch (System.ArgumentNullException)
							{
								System.Console.WriteLine("Binary data array is null.");
							}

							SimpleFingerprint fprint = new SimpleFingerprint();
							fprint.Base64Template = base64String;
							fprint.Filename = uploadedFile.FileName;
							DateTime dateUploaded = DateTime.Now;
							string isoJson = JsonConvert.SerializeObject(dateUploaded, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" });
							fprint.DateUploaded = isoJson;
							//fingerprints.Add (fprint);
							person.simpleFingerprint = fprint;
						}

						person.SimpleFingerprints = fingerprints;

						var json = NServiceKit.Text.JsonSerializer.SerializeToString(person);
						Console.WriteLine(json);
						WebClient client = new WebClient();
						try
						{
							client.UploadString(url, "PUT", json);
						}
						catch (Exception ex)
						{
							Console.WriteLine(ex);
						}
						string jsonString = JsonConvert.SerializeObject(jsonResponse);
						response = jsonString;
					}
					else {
						// Print out any non-null result
						Console.WriteLine("Probe {0} matches registered person {1}", probe.Uuid, match.Uuid);

						// Compute similarity score
						DateTime date4 = DateTime.Now;
						float score = Afis.Verify(probe, match);
						Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Uuid, match.Uuid, score);
						DateTime date5 = DateTime.Now;
						diffInSeconds = (date5 - date4).TotalSeconds;
						Console.WriteLine("Verify time:  " + diffInSeconds + " seconds");
						message = "Match: " + probe.Name + " matches " + match.Name + " Score: " + score;

						jsonResponse.StatusCode = 1;
						jsonResponse.Error = null;
						jsonResponse.UID = match.Uuid;
						jsonResponse.Threshold = score;

						string jsonString = JsonConvert.SerializeObject(jsonResponse);
						response = jsonString;
					}
				}
			}
			else {
				jsonResponse.Error = "Auth error.";
				string jsonString = JsonConvert.SerializeObject(jsonResponse);
				response = jsonString;
			}
			return response;
		}
		public void AddData(MyPerson person)
		{
			lock (people) people.Add(person);
		}
Example #7
0
//		async  Task<ViewQueryResponse<string>> GetPersonListAsync ()
		async  Task GetPersonListAsync (Container container)
		{
			//List<MyPerson> database = new List<MyPerson>();
			//List<MyPerson> database = FilesService.Database;

			//string sourceDirectory = @"/Users/chrisk/source/KiwiRest/RestFiles/App_Data/files";
			//AfisEngine Afis = new AfisEngine();
			DateTime date1 = DateTime.Now;
			Console.WriteLine("Starting FingerprintDatabase:  " + date1);
//			WebClient client = new WebClient ();
			//string uri = "http://localhost:5984/prints/_all_docs&include_docs=true";
			//			string data = client.DownloadString (uri);
			//			var fromJson = JsonSerializer.DeserializeFromString<AllDocs>(data);
			var myCouchClient = new MyCouch.MyCouchClient("http://localhost:5984/prints");
			ViewQueryResponse<string> result = null;
			try 
			{
				var queryView = new QueryViewRequest("_all_docs");
				queryView.Configure(query => query
					.IncludeDocs(true));
				result = await myCouchClient.Views.QueryAsync<string>(queryView);
				var rows = result.Rows;

//				foreach (ViewQueryResponse<SimpleFingerprint> row in rows)
				foreach (ViewQueryResponse<string,string>.Row row in rows)
				{
					Console.WriteLine("Lookin' at " + row);
					string doc = row.IncludedDoc;
					var person = new MyPerson ();
//					SimpleFingerprint print = TypeSerializer.DeserializeFromString<SimpleFingerprint>(doc);
					var jsonObj = JsonSerializer.DeserializeFromString<JsonObject>(doc);
					person._id = jsonObj["_id"];
					var jsonFingerprints = jsonObj["simpleFingerprint"];
					//var Filename = jsonObj["Filename"];
//					var serialFingerprints = JsonSerializer.DeserializeFromString<List<JsonObject>>(jsonFingerprints);
					var serialFingerprints = JsonArrayObjects.Parse(jsonFingerprints);
					//var fps = JsonSerializer.DeserializeFromString<Dictionary<string, string>>(jsonFingerprints);
					//var fp = JsonSerializer.DeserializeFromString<JsonObject>(jsonObj["simpleFingerprint"]);
					//SimpleFingerprint sf = JsonSerializer.DeserializeFromString<SimpleFingerprint>(jsonObj["simpleFingerprint"]);
					List<Fingerprint> fingerprints = new List<Fingerprint> ();
					foreach (KeyValuePair<string,string> pair in serialFingerprints[0]) {
						Fingerprint simpleFingerprint = new Fingerprint ();
						String value = pair.Value;
						if (value != null)
						{
							char[] delimiterChars = { ':' };
							string[] printPair = value.Split(delimiterChars);
							if (printPair[0] == "Base64Template")
							{
								byte[] printArray = System.Convert.FromBase64String(printPair[1]);
								simpleFingerprint.Template = printArray;
								fingerprints.Add(simpleFingerprint);
							}
						}
						//var print = printPair[1];
						//byte[] printArray = System.Convert.FromBase64String(print);
						//simpleFingerprint.Template = printArray;
//						simpleFingerprint.Filename = Filename;
						//fingerprints.Add(simpleFingerprint);
//						foreach (KeyValuePair<string,string> pair in fprint) {
//							SimpleFingerprint simpleFingerprint = new SimpleFingerprint ();
//							var strBase64Template = JsonSerializer.DeserializeFromString<string>(pair.Key);
////							simpleFingerprint.Base64Template = strBase64Template["Base64Template"];
//							fingerprints.Add(simpleFingerprint);
//						}

					}
//					foreach (KeyValuePair<string,string> pair in serialFingerprints)
//					{
//						var prints = JsonSerializer.DeserializeFromString<JsonObject>(pair.Key);
//						foreach (KeyValuePair<string,string> print in prints)
//						{
//							SimpleFingerprint simpleFingerprint = new SimpleFingerprint ();
//							var strBase64Template = JsonSerializer.DeserializeFromString<string>(print.Key);
////							simpleFingerprint.Base64Template = print["Base64Template"];
//							fingerprints.Add(simpleFingerprint);
//						}
//					}
					person.Fingerprints = fingerprints;
					//person.Filename = jsonObj["Filename"];
					person.Uuid = jsonObj["Uuid"];
					//database.Add(person);
					FingerprintDatabase.AddData(person);
					Console.WriteLine("Added person to FingerprintDatabase.");
				}
				//container.Register(database);

			}
			catch (Exception e) {
				Console.WriteLine("Error: " + e);
			}

//			return result;
		}