Exemple #1
0
        /// <summary>
        /// Main entry point. Creates a bunch of services, and then kicks off
        /// the webserver, which is a blocking call (since it's the dispatcher
        /// thread) until the app exits.
        /// </summary>
        /// <param name="listeningPort"></param>
        /// <param name="args"></param>
        private static void StartWebServer(int listeningPort, string[] args)
        {
            try
            {
                Logging.Log("Starting Damselfly Services");

                // Instantiate all of our services
                var status    = new StatusService();
                var thumbs    = new ThumbnailService();
                var indexing  = new IndexingService();
                var downloads = new DownloadService();
                var basket    = new BasketService();
                var folder    = new FolderService();
                var search    = new SearchService();
                var tasks     = new TaskService();
                var config    = new ConfigService();
                var meta      = new MetaDataService();
                var wp        = new WordpressService();
                var proc      = new ImageProcessService();
                var select    = new SelectionService();

                Logging.Log("Starting Damselfly Webserver");

                BuildWebHost(listeningPort, args).Run();

                Logging.Log("Damselfly Webserver stopped. Exiting");
            }
            catch (Exception ex)
            {
                Logging.Log("Damselfly Webserver terminated with exception: {0}", ex.Message);
            }
        }
 public MainForm()
 {
     InitializeComponent();
     _imageProcessService = ImageProcessService.Instance;
     _imageProcessService.OnProgressUpdate  += imageProcessService_OnProgressUpdate;
     _imageProcessService.OnProcessComplete += imageProcessService_OnProcessComplete;
     _selectedFilterValues = new SelectedFilterValues();
     _selectedImageFilter  = new GammaFilter(_selectedFilterValues.Gamma);
 }
Exemple #3
0
    public FolderWatcherService(StatusService statusService,
                                ImageProcessService imageService)
    {
        _statusService       = statusService;
        _imageProcessService = imageService;

        // Start a thread which will periodically drain the queue
        _queueTask = Task.Run(FolderQueueProcessor);
    }
Exemple #4
0
    public WordpressService(ImageProcessService imageService,
                            ConfigService configService,
                            StatusService statusService)
    {
        _configService       = configService;
        _statusService       = statusService;
        _imageProcessService = imageService;

        ResetClient();
    }
Exemple #5
0
    public ThumbnailService(StatusService statusService,
                            ImageProcessService imageService,
                            ImageCache imageCache, WorkService workService)
    {
        _statusService          = statusService;
        _imageProcessingService = imageService;
        _imageCache             = imageCache;
        _workService            = workService;

        _workService.AddJobSource(this);
    }
        public async Task <IActionResult> Face(string faceId, CancellationToken cancel,
                                               [FromServices] ImageProcessService imageProcessor,
                                               [FromServices] ThumbnailService thumbService,
                                               [FromServices] ImageCache imageCache)
        {
            using var db = new ImageContext();

            IActionResult result = Redirect("/no-image.png");

            try
            {
                var query = db.ImageObjects.AsQueryable();

                // TODO Massively optimise this - if the file already exists we don't need the DB
                if (int.TryParse(faceId, out var personId))
                {
                    query = query.Where(x => x.Person.PersonId == personId);
                }
                else
                {
                    query = query.Where(x => x.Person.AzurePersonId == faceId);
                }

                // Sort by largest face picture, then by most recent date taken
                var face = await query
                           .OrderByDescending(x => x.RectWidth)
                           .ThenByDescending(x => x.RectHeight)
                           .ThenByDescending(x => x.Image.SortDate)
                           .FirstOrDefaultAsync();

                if (cancel.IsCancellationRequested)
                {
                    return(result);
                }

                if (face != null)
                {
                    var thumbPath = await thumbService.GenerateFaceThumb(face);

                    if (thumbPath != null && thumbPath.Exists)
                    {
                        result = PhysicalFile(thumbPath.FullName, "image/jpeg");
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogError($"Unable to load face thumbnail for {faceId}: {ex.Message}");
            }

            return(result);
        }
Exemple #7
0
    public IndexingService(StatusService statusService, ImageProcessService imageService,
                           ConfigService config, ImageCache imageCache, FolderWatcherService watcherService,
                           WorkService workService)
    {
        _statusService       = statusService;
        _configService       = config;
        _imageProcessService = imageService;
        _imageCache          = imageCache;
        _workService         = workService;
        _watcherService      = watcherService;

        // Slight hack to work around circular dependencies
        _watcherService.LinkIndexingServiceInstance(this);
    }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.WindowState         = WindowState.Maximized;
            this.MainPageArea.Width  = SystemParameters.PrimaryScreenWidth;
            this.MainPageArea.Height = SystemParameters.PrimaryScreenHeight;

            Panel_stop.Visibility = Visibility.Collapsed;

            PreviewService.previewSetup();
            ImageProcessService.ImgProcessSetup();

            /// Load Yolo Model
            GV.ML_Folders[(int)MLFolders.ML_YOLO_model] = Environment.CurrentDirectory + MLFolders.ML_YOLO_model.GetDescription();
            if (!Directory.Exists(GV.ML_Folders[(int)MLFolders.ML_YOLO_model]))
            {
                Directory.CreateDirectory(GV.ML_Folders[(int)MLFolders.ML_YOLO_model]);
            }

            mYolo.LoadModel(GV.ML_Folders[(int)MLFolders.ML_YOLO_model]);

            PreviewService.startPreview(PreviewService.previewFPS.HIGH);
        }
Exemple #9
0
 public ImageRecognitionService(StatusService statusService, ObjectDetector objectDetector,
                                MetaDataService metadataService, AzureFaceService azureFace,
                                AccordFaceService accordFace, EmguFaceService emguService,
                                ThumbnailService thumbs, ConfigService configService,
                                ImageClassifier imageClassifier, ImageCache imageCache,
                                WorkService workService, ExifService exifService,
                                ImageProcessService imageProcessor)
 {
     _thumbService      = thumbs;
     _accordFaceService = accordFace;
     _azureFaceService  = azureFace;
     _statusService     = statusService;
     _objectDetector    = objectDetector;
     _metdataService    = metadataService;
     _emguFaceService   = emguService;
     _configService     = configService;
     _imageClassifier   = imageClassifier;
     _imageProcessor    = imageProcessor;
     _imageCache        = imageCache;
     _workService       = workService;
     _exifService       = exifService;
 }
Exemple #10
0
        /// <summary>
        /// Called by the Blazor runtime - this is where we setup the HTTP request pipeline and
        /// initialise all the bits and pieces we need to run.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                              DownloadService download, ThemeService themes, TaskService tasks,
                              ExifService exifService, ThumbnailService thumbService,
                              IndexingService indexService, ImageProcessService imageProcessing,
                              AzureFaceService azureFace, ImageRecognitionService aiService,
                              UserService userService, ConfigService configService, WorkService workService,
                              ImageCache imageCache, MetaDataService metaDataService, ObjectDetector objectDetector)
        {
            SyncfusionLicenseProvider.RegisterLicense("NTUxMzEwQDMxMzkyZTM0MmUzMGFRSFpzQUhjdUE2M2V4S1BmYSs5bk13dkpGbkhvam5Wb1VRbGVURkRsOHM9");

            var logLevel = configService.Get(ConfigSettings.LogLevel, Serilog.Events.LogEventLevel.Information);

            Logging.ChangeLogLevel(logLevel);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            if (Logging.Verbose)
            {
                app.UseSerilogRequestLogging();
            }

            app.UseResponseCompression();
            app.UseRouting();
            app.UseResponseCaching();

            // Disable this for now
            // app.UseHttpsRedirection();

            // TODO: Do we need this if we serve all the images via the controller?
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(ThumbnailService.PicturesRoot),
                RequestPath  = ThumbnailService.RequestRoot
            });

            // Enable auth
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapControllerRoute(name: "default", pattern: "{controller}/{action}");
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

            // Prime the cache
            imageCache.WarmUp().Wait();

            // TODO: Save this in ConfigService
            string contentRootPath = Path.Combine(env.ContentRootPath, "wwwroot");

            // TODO: Fix this, or not if Skia doesn't need it
            imageProcessing.SetContentPath(contentRootPath);
            download.SetDownloadPath(contentRootPath);
            themes.SetContentPath(contentRootPath);

            // Start the work processing queue for AI, Thumbs, etc
            workService.StartService();

            // Start the face service before the thumbnail service
            azureFace.StartService().Wait();
            metaDataService.StartService();
            indexService.StartService();
            aiService.StartService();

            // ObjectDetector can throw a segmentation fault if the docker container is pinned
            // to a single CPU, so for now, to aid debugging, let's not even try and initialise
            // it if AI is disabled. See https://github.com/Webreaper/Damselfly/issues/334
            if (!configService.GetBool(ConfigSettings.DisableObjectDetector, false))
            {
                objectDetector.InitScorer();
            }

            // Validation check to ensure at least one user is an Admin
            userService.CheckAdminUser().Wait();

            StartTaskScheduler(tasks, download, thumbService, exifService);

            Logging.StartupCompleted();
            Logging.Log("Starting Damselfly webserver...");
        }
Exemple #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            ImageParam imageParam = this.PrepareData();

            if (!this.ValidateData(imageParam))
            {
                return;
            }

            //开始去水印:获取文件 ,只取第一层级
            List <string> files = new List <string>();

            files.AddRange(Directory.GetFiles(imageParam.PicPath, "*.jpg"));

            foreach (var dir in Directory.GetDirectories(imageParam.PicPath))
            {
                if (dir.EndsWith(targetPath, StringComparison.InvariantCultureIgnoreCase) ||
                    dir.EndsWith(bakpath, StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                files.AddRange(Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories));
            }

            if (!files.Any())
            {
                MessageBox.Show("路径下不存在任何图片");
                return;
            }

            string rootpath    = imageParam.PicPath.TrimEnd('\\');
            string filepattern = $"{rootpath}\\(?<subpath>.*)\\.*.jpg";

            filepattern = filepattern.Replace("\\", "\\\\");

            //多线程处理图片, 默认使用本机处理器数 * 2;
            ParallelOptions parallelOptions = new ParallelOptions
            {
                MaxDegreeOfParallelism = Environment.ProcessorCount * 2
                                         //MaxDegreeOfParallelism = 1
            };

            ImageProcessService service = new ImageProcessService();

            string newtargetpath = Path.Combine(rootpath, targetPath);
            string newbakpath    = Path.Combine(rootpath, bakpath);

            //开始处理图片

            //显示进度条
            progressBar1.Visible = true;
            progressBar1.Value   = 0; //清空进度条
            int len = files.Count, flag = 1;

            Parallel.ForEach(files, parallelOptions, (file) =>
            {
                string fileName = Path.GetFileName(file);
                Match match     = Regex.Match(file, filepattern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    string subPath        = match.Groups["subpath"].Value;
                    string targetFileName = Path.Combine(rootpath, targetPath, subPath, fileName);
                    string bakfilename    = Path.Combine(rootpath, bakpath, subPath, fileName);

                    CreateDirectory(targetFileName);
                    CreateDirectory(bakfilename);

                    //压缩图片,返回图片流
                    using (Image fileStream = Image.FromFile(file))
                    {
                        MemoryStream memoryStream = service.GetImagePress(fileStream, imageParam);
                        //保存图片到新目录
                        Image.FromStream(memoryStream).Save(targetFileName);
                    }

                    //移动旧图到备份目录
                    new FileInfo(file).MoveTo(bakfilename);

                    //如果目录为空,则删除目录
                    //需要考虑多级为空,依次递归删除至顶层目录


                    //展示进度
                    int newbar = Convert.ToInt32(Math.Ceiling(flag++ *100.0 / len));
                    if (progressBar1.Value < newbar)
                    {
                        progressBar1.Value = newbar;
                    }
                }

                //Thread.Sleep(1000);
                Application.DoEvents();
            });

            MessageBox.Show("工作完成!");
        }
 public DownloadService(StatusService statusService, ImageProcessService imageService)
 {
     _statusService          = statusService;
     _imageProcessingService = imageService;
 }