示例#1
0
        private static async Task MainAsync()
        {
            #region OCR.Space

            foreach (var item in SantinhosPoliticos)
            {
                item.TextoOCRSpace = await SpaceHelper.UploadAndRecognizeImage(item.ImageFilePath);

                item.MatchOCRSpace = PesquisarCandidatoTexto(item.NomeCandidato, item.NumeroEleitoral,
                                                             item.TextoOCRSpace);

                // Conta a quantidade de matches para cada tipo de match.
                switch (item.MatchOCRSpace)
                {
                case MatchType.Nome:
                    MatchesOCRSpace.QtdeMatchesNome++;
                    break;

                case MatchType.NumeroEleitoral:
                    MatchesOCRSpace.QtdeMatchesNumeroEleitoral++;
                    break;

                case MatchType.NomeENumeroEleitoral:
                    MatchesOCRSpace.QtdeMatchesNomeENumeroEleitoral++;
                    break;
                }

                Console.WriteLine("{0,-15} {1,15} {2,35} {3,25} {4,20}", DateTime.Now.ToLongTimeString(),
                                  item.NumeroEleitoral, item.NomeCandidato, "OCR.Space", item.MatchOCRSpace);

                Thread.Sleep(5000);
            }

            #endregion

            #region Microsoft Cognitive Service

            foreach (var item in SantinhosPoliticos)
            {
                item.TextoMicrosoftCognitiveServices =
                    await MicrosoftCognitiveServicesHelper.UploadAndRecognizeImage(item.ImageFilePath);

                item.MatchMicrosoftCognitiveServices = PesquisarCandidatoTexto(item.NomeCandidato, item.NumeroEleitoral,
                                                                               item.TextoMicrosoftCognitiveServices);

                // Conta a quantidade de matches para cada tipo de match.
                switch (item.MatchMicrosoftCognitiveServices)
                {
                case MatchType.Nome:
                    MatchesMicrosoftCognitiveServices.QtdeMatchesNome++;
                    break;

                case MatchType.NumeroEleitoral:
                    MatchesMicrosoftCognitiveServices.QtdeMatchesNumeroEleitoral++;
                    break;

                case MatchType.NomeENumeroEleitoral:
                    MatchesMicrosoftCognitiveServices.QtdeMatchesNomeENumeroEleitoral++;
                    break;
                }

                Console.WriteLine("{0,-15} {1,15} {2,35} {3,25} {4,20}", DateTime.Now.ToLongTimeString(),
                                  item.NumeroEleitoral, item.NomeCandidato, "MS Cognitive Services",
                                  item.MatchMicrosoftCognitiveServices);

                Thread.Sleep(5000);
            }

            #endregion
        }
示例#2
0
        public async Task <ActionResult> Index(UploadFotoViewModel viewModel)
        {
            var validImageTypes = new[] { "image/jpeg", "image/pjpeg", "image/png" };

            if (viewModel.ImageUpload == null || viewModel.ImageUpload.ContentLength == 0)
            {
                ModelState.AddModelError("ImageUpload", ValidationErrorMessage.OcorrenciaFotoNotNull);
            }
            else if (!validImageTypes.Contains(viewModel.ImageUpload.ContentType))
            {
                ModelState.AddModelError("ImageUpload", ValidationErrorMessage.OcorrenciaFotoInvalidFormat);
            }

            viewModel.TiposPropaganda = _db.TiposPropaganda.Select(x => new TipoPropagandaViewModel
            {
                TipoPropagandaId = x.TipoPropagandaId,
                Descricao        = x.Descricao
            }).ToList();

            if (ModelState.IsValid)
            {
                var extension = Path.GetExtension(viewModel.ImageUpload.FileName);
                var filePath  = "";

                try
                {
                    var geolocationInfo = new GeolocationInfoFileExtractor(viewModel.ImageUpload.InputStream);
                    var path            =
                        Server.MapPath(
                            $"{WebConfigurationManager.AppSettings["DiretorioFotosSantinhos"]}{User.Identity.Name}/");
                    Directory.CreateDirectory(path);
                    filePath         = $"{path}{Guid.NewGuid()}{extension}";
                    ViewBag.FilePath = filePath;
                    viewModel.ImageUpload.SaveAs(filePath);

                    var googleGeocoder = new GoogleGeocoder(WebConfigurationManager.AppSettings["GoogleMapsAPIKey"]);
                    var enderecos      = googleGeocoder.ReverseGeocode(geolocationInfo.Latitude, geolocationInfo.Longitude);
                    var endereco       =
                        enderecos.Where(
                            e =>
                            e.LocationType == GoogleLocationType.Rooftop ||
                            e.LocationType == GoogleLocationType.RangeInterpolated).Select(x => new Endereco
                    {
                        EnderecoFormatado = x.FormattedAddress,
                        Latitude          = x.Coordinates.Latitude,
                        Longitude         = x.Coordinates.Longitude,
                        Estado            = x[GoogleAddressType.AdministrativeAreaLevel1].ShortName,
                        Cidade            = x[GoogleAddressType.Locality].LongName,
                        CEP    = x[GoogleAddressType.PostalCode].LongName,
                        Bairro = x[GoogleAddressType.SubLocality].LongName
                    }).FirstOrDefault();

                    var imageText = await MicrosoftCognitiveServicesHelper.UploadAndRecognizeImage(filePath);

                    // Busca o(s) candidato(s) da cidade onde a foto foi tirada
                    var candidatos = _db.Candidatos.Include(c => c.Eleicao)
                                     .Where(c => c.DescricaoUnidadeEleitoral == endereco.Cidade && c.Eleicao.Enabled)
                                     .ToList();

                    var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
                    var match       = false;

                    foreach (var candidato in candidatos)
                    {
                        //var matchByNomeUrna = compareInfo.IndexOf(imageText, candidato.NomeUrna, CompareOptions.IgnoreNonSpace) > -1;
                        //var matchByNumeroEleitoral = compareInfo.IndexOf(imageText, candidato.NumeroEleitoral.ToString(), CompareOptions.IgnoreNonSpace) > -1;

                        //if (matchByNomeUrna && matchByNumeroEleitoral)
                        //    ocorrenciaTipoMatch = OcorrenciaTipoMatch.NomeUrnaENumeroEleitoral;
                        //else if (matchByNomeUrna)
                        //    ocorrenciaTipoMatch = OcorrenciaTipoMatch.NomeUrna;
                        //else if (matchByNumeroEleitoral)
                        //    ocorrenciaTipoMatch = OcorrenciaTipoMatch.NumeroEleitoral;

                        var ocorrenciaTipoMatch = PesquisarCandidatoTexto(candidato.NomeUrna, candidato.NumeroEleitoral, imageText);

                        if (ocorrenciaTipoMatch.HasValue)
                        {
                            match = true;
                            viewModel.CandidatosEncontrados.Add(candidato.NomeUrna);

                            _db.Ocorrencias.Add(new Ocorrencia
                            {
                                FotoPath            = filePath,
                                TipoPropagandaId    = viewModel.TipoPropaganda,
                                OcorrenciaTipoMatch = ocorrenciaTipoMatch,
                                Endereco            = endereco,
                                CandidatoId         = candidato.CandidatoId
                            });
                        }
                    }

                    if (!match)
                    {
                        _db.Ocorrencias.Add(new Ocorrencia
                        {
                            FotoPath         = filePath,
                            TipoPropagandaId = viewModel.TipoPropaganda,
                            Endereco         = endereco
                        });
                    }

                    _db.SaveChanges();
                    ViewBag.FotoSalva = true;
                }
                catch (GoogleGeocodingException)
                {
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }

                    ViewBag.ErrorMessage = ValidationErrorMessage.UploadFotoGoogleGeocodingException;
                    return(View(viewModel));
                }
                catch (Exception ex)
                {
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }

                    ViewBag.ErrorMessage = ex.Message;
                    return(View(viewModel));
                }
            }

            viewModel.CandidatosEncontrados = viewModel.CandidatosEncontrados.OrderBy(c => c).ToList();
            return(View(viewModel));
        }