├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md └── src ├── Icons ├── icons8-checkbox-markiert-2-500.ico ├── icons8-checkbox-markiert-2-500.png ├── icons8-checkbox-markiert-2-filled-500.ico ├── icons8-checkbox-markiert-2-filled-500.png ├── icons8-fernglas-500 gefüllt.ico ├── icons8-fernglas-500-weiß.ico ├── icons8-fernglas-500-weiß.png ├── icons8-fernglas-500.ico ├── icons8-fernglas-500.png ├── icons8-fernglas-filled-500-weiß.ico ├── icons8-fernglas-filled-500-weiß.png ├── icons8-fernglas-filled-500.ico ├── icons8-fernglas-filled-500.png ├── icons8-geprüft-500.ico ├── icons8-geprüft-500.png ├── icons8-geprüft-filled-500.ico ├── icons8-geprüft-filled-500.png ├── icons8-häkchen-500.ico ├── icons8-häkchen-500.png ├── icons8-häkchen-filled-500.ico ├── icons8-häkchen-filled-500.png ├── icons8-löschen-500.ico ├── icons8-löschen-500.png ├── icons8-löschen-filled-500.ico ├── icons8-löschen-filled-500.png ├── icons8-ok-500.ico ├── icons8-ok-500.png ├── icons8-ok-filled-500.ico ├── icons8-ok-filled-500.png ├── icons8-plus-500.ico ├── icons8-plus-500.png ├── icons8-plus-filled-500.ico ├── icons8-plus-filled-500.png ├── icons8-stornieren-500.ico ├── icons8-stornieren-500.png ├── icons8-stornieren-filled-500.ico ├── icons8-stornieren-filled-500.png ├── logo.ico ├── logo.png └── save.png ├── UI ├── App.config ├── Camera.cs ├── InputForm.Designer.cs ├── InputForm.cs ├── InputForm.resx ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── Resources │ ├── airplane.png │ ├── bear.png │ ├── bicycle.png │ ├── bird.png │ ├── boat.png │ ├── bus.png │ ├── car.png │ ├── cat.png │ ├── cow.png │ ├── dog.png │ ├── horse.png │ ├── logo.png │ ├── motorcycle.png │ ├── person.png │ ├── sheep.png │ └── truck.png ├── Shell.Designer.cs ├── Shell.cs ├── Shell.resx ├── UI.csproj ├── logo.ico └── packages.config └── bi-aidetection.sln /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AI Detection for Blue Iris 2 | Alarm system for Blue Iris based on Artificial Intellience. Can send alerts to Telegram. 3 | 4 | ### Updated Fork Available 5 | https://github.com/VorlonCD/bi-aidetection 6 | 7 | VorlonCD's fork has added many features and fixed many bugs present here, we recommend his fork for the latest on this program. 8 | 9 | ### Download 10 | https://github.com/gentlepumpkin/bi-aidetection/releases 11 | Click "> Assets" to find the .zip file. 12 | 13 | ### Install guide and discussion 14 | https://ipcamtalk.com/threads/tool-tutorial-free-ai-person-detection-for-blue-iris.37330/ 15 | 16 | ### Key Features 17 | - analyze Blue Iris motion alerts using Artificial Intelligence and sort out false alerts 18 | - detect humans and selected objects 19 | - send alert images to Telegram using a bot (optional) 20 | - one alert image per event 21 | - statistics and individual configuration for every camera 22 | 23 | ### Screenshot 24 | ![Screenshot](https://ipcamtalk.com/attachments/processing1-53-png.44807/) 25 | 26 | ### How to contribute 27 | 1. install Visual Studio 28 | 2. download project as .zip and unpack somewhere 29 | 3. go to ./src/ and open bi-aidetection.sln with Visual Studio. 30 | 31 | Using the Github extension for Visual Studio: 32 | 1. install Visual Studio 33 | 1. install Github Extension from here https://visualstudio.github.com/ 34 | 2. Click the green button "clone or download" above this text 35 | 3. Select "Open in Visual Studio" 36 | -------------------------------------------------------------------------------- /src/Icons/icons8-checkbox-markiert-2-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-checkbox-markiert-2-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-checkbox-markiert-2-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-checkbox-markiert-2-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-checkbox-markiert-2-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-checkbox-markiert-2-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-checkbox-markiert-2-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-checkbox-markiert-2-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-500 gefüllt.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-500 gefüllt.ico -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-500-weiß.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-500-weiß.ico -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-500-weiß.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-500-weiß.png -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-filled-500-weiß.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-filled-500-weiß.ico -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-filled-500-weiß.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-filled-500-weiß.png -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-fernglas-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-fernglas-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-geprüft-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-geprüft-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-geprüft-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-geprüft-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-geprüft-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-geprüft-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-geprüft-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-geprüft-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-häkchen-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-häkchen-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-häkchen-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-häkchen-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-häkchen-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-häkchen-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-häkchen-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-häkchen-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-löschen-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-löschen-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-löschen-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-löschen-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-löschen-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-löschen-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-löschen-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-löschen-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-ok-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-ok-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-ok-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-ok-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-ok-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-ok-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-ok-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-ok-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-plus-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-plus-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-plus-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-plus-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-plus-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-plus-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-plus-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-plus-filled-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-stornieren-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-stornieren-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-stornieren-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-stornieren-500.png -------------------------------------------------------------------------------- /src/Icons/icons8-stornieren-filled-500.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-stornieren-filled-500.ico -------------------------------------------------------------------------------- /src/Icons/icons8-stornieren-filled-500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/icons8-stornieren-filled-500.png -------------------------------------------------------------------------------- /src/Icons/logo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/logo.ico -------------------------------------------------------------------------------- /src/Icons/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/logo.png -------------------------------------------------------------------------------- /src/Icons/save.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/Icons/save.png -------------------------------------------------------------------------------- /src/UI/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 127.0.0.1:81 25 | 26 | 27 | False 28 | 29 | 30 | True 31 | 32 | 33 | -1 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/UI/Camera.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | using System.IO; 8 | 9 | namespace WindowsFormsApp2 10 | { 11 | class Camera 12 | { 13 | public string name; 14 | public string prefix; 15 | public string triggering_objects_as_string; 16 | public string[] triggering_objects; 17 | public string trigger_urls_as_string; 18 | public string[] trigger_urls; 19 | public bool telegram_enabled; 20 | public bool enabled; 21 | public DateTime last_trigger_time; 22 | public double cooldown_time; 23 | public int threshold_lower; 24 | public int threshold_upper; 25 | 26 | public List last_detections = new List(); //stores objects that were detected last 27 | public List last_confidences = new List(); //stores last objects confidences 28 | public List last_positions = new List(); //stores last objects positions 29 | public String last_detections_summary; //summary text of last detection 30 | 31 | 32 | //stats 33 | public int stats_alerts; //alert image contained relevant object counter 34 | public int stats_false_alerts; //alert image contained no object counter 35 | public int stats_irrelevant_alerts; //alert image contained irrelevant object counter 36 | 37 | //write config to file 38 | public void WriteConfig(string _name, string _prefix, string _triggering_objects_as_string, string _trigger_urls_as_string, bool _telegram_enabled, bool _enabled, double _cooldown_time, int _threshold_lower, int _threshold_upper) 39 | { 40 | //if camera name (= settings file name) changed, the old settings file must be deleted 41 | if(name != _name) 42 | { 43 | System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + $"/cameras/{ name }.txt"); 44 | } 45 | 46 | //write config file 47 | using (StreamWriter sw = System.IO.File.CreateText(AppDomain.CurrentDomain.BaseDirectory + $"/cameras/{ _name }.txt")) 48 | { 49 | name = _name; 50 | prefix = _prefix; 51 | triggering_objects_as_string = _triggering_objects_as_string; 52 | trigger_urls_as_string = _trigger_urls_as_string; 53 | telegram_enabled = _telegram_enabled; 54 | enabled = _enabled; 55 | cooldown_time = _cooldown_time; 56 | threshold_lower = _threshold_lower; 57 | threshold_upper = _threshold_upper; 58 | 59 | 60 | triggering_objects = triggering_objects_as_string.Split(','); //split the row of triggering objects between every ',' 61 | 62 | trigger_urls = trigger_urls_as_string.Replace(" ", "").Split(','); //all trigger urls in an array 63 | trigger_urls = trigger_urls.Except(new string[] { "" }).ToArray(); //remove empty entries 64 | 65 | //rewrite trigger_urls_as_string without possible empty entires 66 | int i = 0; 67 | trigger_urls_as_string = ""; 68 | foreach (string c in trigger_urls) 69 | { 70 | trigger_urls_as_string += c; 71 | if(i < (trigger_urls.Length - 1)) 72 | { 73 | trigger_urls_as_string += ", "; 74 | } 75 | i++; 76 | } 77 | 78 | sw.WriteLine($"Trigger URL(s): \"{trigger_urls_as_string.Replace(", ,", "")}\" (input one or multiple urls, leave empty to disable; format: \"url, url, url\", example: \"http://192.168.1.133:80/admin?trigger&camera=frontyard&user=admin&pw=secretpassword, http://google.com\")"); 79 | sw.WriteLine($"Relevant objects: \"{triggering_objects_as_string}\" (format: \"object, object, ...\", options: see below, example: \"person, bicycle, car\")"); 80 | sw.WriteLine($"Input file begins with: \"{prefix}\" (only analyze images which names start with this text, leave empty to disable the feature, example: \"backyardcam\")"); 81 | if (telegram_enabled == true) 82 | { 83 | sw.WriteLine("Send images to Telegram: \"yes\"(options: yes, no)"); 84 | } 85 | else 86 | { 87 | sw.WriteLine("Send images to Telegram: \"no\"(options: yes, no)"); 88 | } 89 | 90 | if (enabled == true) 91 | { 92 | sw.WriteLine("ai detection enabled?: \"yes\"(options: yes, no)"); 93 | } 94 | else 95 | { 96 | sw.WriteLine("ai detection enabled?: \"no\"(options: yes, no)"); 97 | } 98 | sw.WriteLine($"Cooldown time: \"{cooldown_time}\" minutes (How many minutes must have passed since the last detection. Used to separate event to ensure that every event only causes one alert.)"); 99 | sw.WriteLine($"Certainty threshold: \"{threshold_lower},{threshold_upper}\" (format: \"lower % limit, upper % limit\")"); 100 | sw.WriteLine($"STATS: alerts,irrelevant alerts,false alerts: \"{stats_alerts.ToString()}, {stats_irrelevant_alerts.ToString()}, {stats_false_alerts.ToString()}\" "); 101 | 102 | 103 | } 104 | } 105 | 106 | //delete config file 107 | public void Delete() 108 | { 109 | System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + $"/cameras/{ this.name }.txt"); 110 | } 111 | 112 | //read config from file 113 | public void ReadConfig(string config_path) 114 | { 115 | //retrieve whole config file content 116 | string[] content = System.IO.File.ReadAllLines(config_path); 117 | 118 | //import config data into variables, cut out relevant data between " " 119 | name = Path.GetFileNameWithoutExtension(config_path); 120 | prefix = content[2].Split('"')[1]; 121 | 122 | //read triggering objects 123 | triggering_objects_as_string = content[1].Split('"')[1].Replace(" ", ""); //take the second line, split it between every ", take the part after the first ", remove every " " in this part 124 | triggering_objects = triggering_objects_as_string.Split(','); //split the row of triggering objects between every ',' 125 | 126 | 127 | //read trigger urls 128 | trigger_urls_as_string = content[0].Split('"')[1]; //takes the first line, cuts out everything between the first and the second " marker; all trigger urls in one string, ! still contains possible spaces etc. 129 | trigger_urls = trigger_urls_as_string.Replace(" ", "").Split(','); //all trigger urls in an array 130 | trigger_urls = trigger_urls.Except(new string[] { "" }).ToArray(); //remove empty entries 131 | 132 | //rewrite trigger_urls_as_string without possible empty entires 133 | int i = 0; 134 | trigger_urls_as_string = ""; 135 | foreach (string c in trigger_urls) 136 | { 137 | trigger_urls_as_string += c; 138 | if (i < (trigger_urls.Length - 1)) 139 | { 140 | trigger_urls_as_string += ", "; 141 | } 142 | i++; 143 | } 144 | 145 | //read telegram enabled 146 | if (content[3].Split('"')[1].Replace(" ", "") == "yes") 147 | { 148 | telegram_enabled = true; 149 | } 150 | else 151 | { 152 | telegram_enabled = false; 153 | } 154 | 155 | //read enabled 156 | if (content[4].Split('"')[1].Replace(" ", "") == "yes") 157 | { 158 | enabled = true; 159 | } 160 | else 161 | { 162 | enabled = false; 163 | } 164 | 165 | Double.TryParse(content[5].Split('"')[1], out cooldown_time); //read cooldown time 166 | 167 | //read lower and upper threshold. Only load if line containing threshold values already exists (>version 1.58). 168 | if (content[6] != "") 169 | { 170 | Int32.TryParse(content[6].Split('"')[1].Split(',')[0], out threshold_lower); //read lower threshold 171 | Int32.TryParse(content[6].Split('"')[1].Split(',')[1], out threshold_upper); //read upper threshold 172 | } 173 | else //if config file from older version, set values to 0% and 100% 174 | { 175 | threshold_lower = 0; 176 | threshold_upper = 100; 177 | } 178 | 179 | 180 | //read stats 181 | Int32.TryParse(content[7].Split('"')[1].Split(',')[0], out stats_alerts); //bedeutet: Zeile 7 (6+1), aufgetrennt an ", 2tes (1+1) Resultat, aufgeteilt an ',', davon 1. Resultat 182 | Int32.TryParse(content[7].Split('"')[1].Split(',')[1], out stats_irrelevant_alerts); 183 | Int32.TryParse(content[7].Split('"')[1].Split(',')[2], out stats_false_alerts); 184 | } 185 | 186 | 187 | //one correct alarm counter 188 | public void IncrementAlerts() 189 | { 190 | stats_alerts++; 191 | WriteConfig(name, prefix, triggering_objects_as_string, trigger_urls_as_string, telegram_enabled, enabled, cooldown_time, threshold_lower, threshold_upper); 192 | } 193 | 194 | //one alarm that contained no objects counter 195 | public void IncrementFalseAlerts() 196 | { 197 | stats_false_alerts++; 198 | WriteConfig(name, prefix, triggering_objects_as_string, trigger_urls_as_string, telegram_enabled, enabled, cooldown_time, threshold_lower, threshold_upper); 199 | } 200 | 201 | //one alarm that contained irrelevant objects counter 202 | public void IncrementIrrelevantAlerts() 203 | { 204 | stats_irrelevant_alerts++; 205 | WriteConfig(name, prefix, triggering_objects_as_string, trigger_urls_as_string, telegram_enabled, enabled, cooldown_time, threshold_lower, threshold_upper); 206 | } 207 | 208 | 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /src/UI/InputForm.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace WindowsFormsApp2 2 | { 3 | partial class InputForm 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.lbl_1 = new System.Windows.Forms.Label(); 32 | this.tb_1 = new System.Windows.Forms.TextBox(); 33 | this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); 34 | this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); 35 | this.btn_2 = new System.Windows.Forms.Button(); 36 | this.btn_1 = new System.Windows.Forms.Button(); 37 | this.tableLayoutPanel1.SuspendLayout(); 38 | this.tableLayoutPanel2.SuspendLayout(); 39 | this.SuspendLayout(); 40 | // 41 | // lbl_1 42 | // 43 | this.lbl_1.Anchor = System.Windows.Forms.AnchorStyles.None; 44 | this.lbl_1.AutoSize = true; 45 | this.lbl_1.Location = new System.Drawing.Point(170, 26); 46 | this.lbl_1.Name = "lbl_1"; 47 | this.lbl_1.Size = new System.Drawing.Size(35, 13); 48 | this.lbl_1.TabIndex = 0; 49 | this.lbl_1.Text = "label1"; 50 | // 51 | // tb_1 52 | // 53 | this.tb_1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); 54 | this.tb_1.Location = new System.Drawing.Point(20, 87); 55 | this.tb_1.Margin = new System.Windows.Forms.Padding(20, 3, 20, 3); 56 | this.tb_1.Name = "tb_1"; 57 | this.tb_1.Size = new System.Drawing.Size(335, 20); 58 | this.tb_1.TabIndex = 1; 59 | this.tb_1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tb_1_KeyDown); 60 | // 61 | // tableLayoutPanel1 62 | // 63 | this.tableLayoutPanel1.ColumnCount = 1; 64 | this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); 65 | this.tableLayoutPanel1.Controls.Add(this.lbl_1, 0, 0); 66 | this.tableLayoutPanel1.Controls.Add(this.tb_1, 0, 1); 67 | this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 2); 68 | this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; 69 | this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); 70 | this.tableLayoutPanel1.Name = "tableLayoutPanel1"; 71 | this.tableLayoutPanel1.RowCount = 3; 72 | this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F)); 73 | this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F)); 74 | this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 40F)); 75 | this.tableLayoutPanel1.Size = new System.Drawing.Size(375, 218); 76 | this.tableLayoutPanel1.TabIndex = 3; 77 | // 78 | // tableLayoutPanel2 79 | // 80 | this.tableLayoutPanel2.ColumnCount = 2; 81 | this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); 82 | this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); 83 | this.tableLayoutPanel2.Controls.Add(this.btn_2, 0, 0); 84 | this.tableLayoutPanel2.Controls.Add(this.btn_1, 0, 0); 85 | this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; 86 | this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 133); 87 | this.tableLayoutPanel2.Name = "tableLayoutPanel2"; 88 | this.tableLayoutPanel2.RowCount = 1; 89 | this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); 90 | this.tableLayoutPanel2.Size = new System.Drawing.Size(369, 82); 91 | this.tableLayoutPanel2.TabIndex = 2; 92 | // 93 | // btn_2 94 | // 95 | this.btn_2.Anchor = System.Windows.Forms.AnchorStyles.None; 96 | this.btn_2.Location = new System.Drawing.Point(239, 29); 97 | this.btn_2.Name = "btn_2"; 98 | this.btn_2.Size = new System.Drawing.Size(75, 23); 99 | this.btn_2.TabIndex = 4; 100 | this.btn_2.Text = "Cancel"; 101 | this.btn_2.UseVisualStyleBackColor = true; 102 | this.btn_2.Click += new System.EventHandler(this.btn_2_Click); 103 | // 104 | // btn_1 105 | // 106 | this.btn_1.Anchor = System.Windows.Forms.AnchorStyles.None; 107 | this.btn_1.Location = new System.Drawing.Point(54, 29); 108 | this.btn_1.Name = "btn_1"; 109 | this.btn_1.Size = new System.Drawing.Size(75, 23); 110 | this.btn_1.TabIndex = 3; 111 | this.btn_1.Text = "Ok"; 112 | this.btn_1.UseVisualStyleBackColor = true; 113 | this.btn_1.Click += new System.EventHandler(this.btn_1_Click); 114 | this.btn_1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.btn_1_KeyDown); 115 | // 116 | // InputForm 117 | // 118 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 119 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 120 | this.ClientSize = new System.Drawing.Size(375, 218); 121 | this.ControlBox = false; 122 | this.Controls.Add(this.tableLayoutPanel1); 123 | this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; 124 | this.MaximizeBox = false; 125 | this.MinimizeBox = false; 126 | this.Name = "InputForm"; 127 | this.ShowInTaskbar = false; 128 | this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; 129 | this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; 130 | this.Text = "InputForm"; 131 | this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.InputForm_KeyDown_1); 132 | this.tableLayoutPanel1.ResumeLayout(false); 133 | this.tableLayoutPanel1.PerformLayout(); 134 | this.tableLayoutPanel2.ResumeLayout(false); 135 | this.ResumeLayout(false); 136 | 137 | } 138 | 139 | #endregion 140 | 141 | private System.Windows.Forms.Label lbl_1; 142 | private System.Windows.Forms.TextBox tb_1; 143 | private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; 144 | private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; 145 | private System.Windows.Forms.Button btn_2; 146 | private System.Windows.Forms.Button btn_1; 147 | } 148 | } -------------------------------------------------------------------------------- /src/UI/InputForm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows.Forms; 10 | 11 | namespace WindowsFormsApp2 12 | { 13 | public partial class InputForm : Form 14 | { 15 | public string text = ""; 16 | 17 | public InputForm(string label, string title, bool show_textbox) 18 | { 19 | InitializeComponent(); 20 | lbl_1.Text = label; 21 | this.Text = title; 22 | if (show_textbox) 23 | { 24 | tb_1.Show(); 25 | } 26 | else 27 | { 28 | tb_1.Hide(); 29 | } 30 | } 31 | 32 | public InputForm(string label, string title, bool show_textbox, string text_OK, string text_Cancel) 33 | { 34 | InitializeComponent(); 35 | lbl_1.Text = label; 36 | this.Text = title; 37 | if (show_textbox) 38 | { 39 | tb_1.Show(); 40 | } 41 | else 42 | { 43 | tb_1.Hide(); 44 | } 45 | btn_1.Text = text_OK; 46 | btn_2.Text = text_Cancel; 47 | } 48 | 49 | private void btn_2_Click(object sender, EventArgs e) 50 | { 51 | this.DialogResult = DialogResult.Cancel; 52 | this.Close(); 53 | } 54 | 55 | private void btn_1_Click(object sender, EventArgs e) 56 | { 57 | text = tb_1.Text; 58 | this.DialogResult = DialogResult.OK; 59 | this.Close(); 60 | } 61 | 62 | private void InputForm_KeyDown_1(object sender, KeyEventArgs e) 63 | { 64 | if (e.KeyCode == Keys.Escape) 65 | { 66 | this.DialogResult = DialogResult.Cancel; 67 | this.Close(); 68 | } 69 | if (e.KeyCode == Keys.Enter) 70 | { 71 | text = tb_1.Text; 72 | this.DialogResult = DialogResult.OK; 73 | this.Close(); 74 | } 75 | } 76 | 77 | private void tb_1_KeyDown(object sender, KeyEventArgs e) 78 | { 79 | if (e.KeyCode == Keys.Escape) 80 | { 81 | this.DialogResult = DialogResult.Cancel; 82 | this.Close(); 83 | } 84 | if (e.KeyCode == Keys.Enter) 85 | { 86 | text = tb_1.Text; 87 | this.DialogResult = DialogResult.OK; 88 | this.Close(); 89 | } 90 | } 91 | 92 | private void btn_1_KeyDown(object sender, KeyEventArgs e) 93 | { 94 | if (e.KeyCode == Keys.Escape) 95 | { 96 | this.DialogResult = DialogResult.Cancel; 97 | this.Close(); 98 | } 99 | if (e.KeyCode == Keys.Enter) 100 | { 101 | text = tb_1.Text; 102 | this.DialogResult = DialogResult.OK; 103 | this.Close(); 104 | } 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/UI/InputForm.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /src/UI/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using System.Windows.Forms; 6 | 7 | namespace WindowsFormsApp2 8 | { 9 | static class Program 10 | { 11 | /// 12 | /// Der Haupteinstiegspunkt für die Anwendung. 13 | /// 14 | [STAThread] 15 | 16 | 17 | static void Main() 18 | { 19 | Application.EnableVisualStyles(); 20 | Application.SetCompatibleTextRenderingDefault(false); 21 | Application.Run(new Shell()); 22 | 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/UI/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Allgemeine Informationen über eine Assembly werden über die folgenden 6 | // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, 7 | // die einer Assembly zugeordnet sind. 8 | [assembly: AssemblyTitle("WindowsFormsApp2")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("WindowsFormsApp2")] 13 | [assembly: AssemblyCopyright("Copyright © 2019")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly 18 | // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von 19 | // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. 20 | [assembly: ComVisible(false)] 21 | 22 | // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird 23 | [assembly: Guid("b8acbd49-0830-4e34-b5b6-c876beae6f65")] 24 | 25 | // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: 26 | // 27 | // Hauptversion 28 | // Nebenversion 29 | // Buildnummer 30 | // Revision 31 | // 32 | // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, 33 | // übernehmen, indem Sie "*" eingeben: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/UI/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // Dieser Code wurde von einem Tool generiert. 4 | // Laufzeitversion:4.0.30319.42000 5 | // 6 | // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn 7 | // der Code erneut generiert wird. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WindowsFormsApp2.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. 17 | /// 18 | // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert 19 | // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. 20 | // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen 21 | // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp2.Properties.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle 51 | /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap. 65 | /// 66 | internal static System.Drawing.Bitmap logo { 67 | get { 68 | object obj = ResourceManager.GetObject("logo", resourceCulture); 69 | return ((System.Drawing.Bitmap)(obj)); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/UI/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 122 | ..\Resources\logo.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 123 | 124 | -------------------------------------------------------------------------------- /src/UI/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // Dieser Code wurde von einem Tool generiert. 4 | // Laufzeitversion:4.0.30319.42000 5 | // 6 | // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn 7 | // der Code erneut generiert wird. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace WindowsFormsApp2.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | 26 | [global::System.Configuration.UserScopedSettingAttribute()] 27 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 28 | [global::System.Configuration.DefaultSettingValueAttribute("")] 29 | public string telegram_token { 30 | get { 31 | return ((string)(this["telegram_token"])); 32 | } 33 | set { 34 | this["telegram_token"] = value; 35 | } 36 | } 37 | 38 | [global::System.Configuration.UserScopedSettingAttribute()] 39 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 40 | [global::System.Configuration.DefaultSettingValueAttribute("")] 41 | public string telegram_chatid { 42 | get { 43 | return ((string)(this["telegram_chatid"])); 44 | } 45 | set { 46 | this["telegram_chatid"] = value; 47 | } 48 | } 49 | 50 | [global::System.Configuration.UserScopedSettingAttribute()] 51 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 52 | [global::System.Configuration.DefaultSettingValueAttribute("")] 53 | public string input_path { 54 | get { 55 | return ((string)(this["input_path"])); 56 | } 57 | set { 58 | this["input_path"] = value; 59 | } 60 | } 61 | 62 | [global::System.Configuration.UserScopedSettingAttribute()] 63 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 64 | [global::System.Configuration.DefaultSettingValueAttribute("127.0.0.1:81")] 65 | public string deepstack_url { 66 | get { 67 | return ((string)(this["deepstack_url"])); 68 | } 69 | set { 70 | this["deepstack_url"] = value; 71 | } 72 | } 73 | 74 | [global::System.Configuration.UserScopedSettingAttribute()] 75 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 76 | [global::System.Configuration.DefaultSettingValueAttribute("False")] 77 | public bool log_everything { 78 | get { 79 | return ((bool)(this["log_everything"])); 80 | } 81 | set { 82 | this["log_everything"] = value; 83 | } 84 | } 85 | 86 | [global::System.Configuration.UserScopedSettingAttribute()] 87 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 88 | [global::System.Configuration.DefaultSettingValueAttribute("True")] 89 | public bool send_errors { 90 | get { 91 | return ((bool)(this["send_errors"])); 92 | } 93 | set { 94 | this["send_errors"] = value; 95 | } 96 | } 97 | 98 | [global::System.Configuration.UserScopedSettingAttribute()] 99 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 100 | [global::System.Configuration.DefaultSettingValueAttribute("-1")] 101 | public int close_instantly { 102 | get { 103 | return ((int)(this["close_instantly"])); 104 | } 105 | set { 106 | this["close_instantly"] = value; 107 | } 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/UI/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 127.0.0.1:81 16 | 17 | 18 | False 19 | 20 | 21 | True 22 | 23 | 24 | -1 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/UI/Resources/airplane.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/airplane.png -------------------------------------------------------------------------------- /src/UI/Resources/bear.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/bear.png -------------------------------------------------------------------------------- /src/UI/Resources/bicycle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/bicycle.png -------------------------------------------------------------------------------- /src/UI/Resources/bird.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/bird.png -------------------------------------------------------------------------------- /src/UI/Resources/boat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/boat.png -------------------------------------------------------------------------------- /src/UI/Resources/bus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/bus.png -------------------------------------------------------------------------------- /src/UI/Resources/car.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/car.png -------------------------------------------------------------------------------- /src/UI/Resources/cat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/cat.png -------------------------------------------------------------------------------- /src/UI/Resources/cow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/cow.png -------------------------------------------------------------------------------- /src/UI/Resources/dog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/dog.png -------------------------------------------------------------------------------- /src/UI/Resources/horse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/horse.png -------------------------------------------------------------------------------- /src/UI/Resources/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/logo.png -------------------------------------------------------------------------------- /src/UI/Resources/motorcycle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/motorcycle.png -------------------------------------------------------------------------------- /src/UI/Resources/person.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/person.png -------------------------------------------------------------------------------- /src/UI/Resources/sheep.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/sheep.png -------------------------------------------------------------------------------- /src/UI/Resources/truck.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/Resources/truck.png -------------------------------------------------------------------------------- /src/UI/Shell.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows.Forms; 10 | using System.Configuration; 11 | 12 | using System.IO; 13 | using System.Net.Http; 14 | using System.Net; 15 | 16 | using Newtonsoft.Json; //deserialize DeepquestAI response 17 | 18 | //for image cutting 19 | using SixLabors.ImageSharp; 20 | using SixLabors.ImageSharp.Processing; 21 | using SixLabors.Primitives; 22 | 23 | //for telegram 24 | using Telegram.Bot; 25 | using Telegram.Bot.Args; 26 | using Telegram.Bot.Types; 27 | using Telegram.Bot.Types.Enums; 28 | using Telegram.Bot.Types.InputFiles; 29 | 30 | using Microsoft.WindowsAPICodePack.Dialogs; 31 | using Size = SixLabors.Primitives.Size; 32 | using SizeF = SixLabors.Primitives.SizeF; //for file dialog 33 | 34 | 35 | namespace WindowsFormsApp2 36 | { 37 | 38 | public partial class Shell : Form 39 | { 40 | public string input_path = Properties.Settings.Default.input_path; //image input path 41 | public static string deepstack_url = Properties.Settings.Default.deepstack_url; //deepstack url 42 | public static bool log_everything = Properties.Settings.Default.log_everything; //save every action sent to Log() into the log file? 43 | public static bool send_errors = Properties.Settings.Default.send_errors; //send error messages to Telegram? 44 | public static string telegram_chatid = Properties.Settings.Default.telegram_chatid; //telegram chat id 45 | public static string[] telegram_chatids = telegram_chatid.Replace(" ", "").Split(','); //for multiple Telegram chats that receive alert images 46 | public static string telegram_token = Properties.Settings.Default.telegram_token; //telegram bot token 47 | public int errors = 0; //error counter 48 | public bool detection_running = false; //is detection running right now or not 49 | public int file_access_delay = 10; //delay before accessing new file in ms 50 | public int retry_delay = 10; //delay for first file acess retry - will increase on each retry 51 | List CameraList = new List(); //list containing all cameras 52 | 53 | static HttpClient client = new HttpClient(); 54 | 55 | FileSystemWatcher watcher = new FileSystemWatcher(); //fswatcher checking the input folder for new images 56 | 57 | public Shell() 58 | { 59 | InitializeComponent(); 60 | 61 | this.Resize += new System.EventHandler(this.Form1_Resize); //resize event to enable 'minimize to tray' 62 | 63 | //if camera settings folder does not exist, create it 64 | if (!Directory.Exists("./cameras/")) 65 | { 66 | //create folder 67 | DirectoryInfo di = Directory.CreateDirectory("./cameras"); 68 | Log("./cameras/" + " dir created."); 69 | } 70 | 71 | //--------------------------------------------------------------------------- 72 | //CAMERAS TAB 73 | 74 | //left list column setup 75 | list2.Columns.Add("Camera"); 76 | 77 | //set left list column width segmentation (because of some bug -4 is necessary to achieve the correct width) 78 | list2.Columns[0].Width = list2.Width - 4; 79 | list2.FullRowSelect = true; //make all columns clickable 80 | 81 | LoadCameras(); //load camera list 82 | 83 | this.Opacity = 0; 84 | this.Show(); 85 | 86 | //--------------------------------------------------------------------------- 87 | //HISTORY TAB 88 | 89 | //left list column setup 90 | list1.Columns.Add("Name"); 91 | list1.Columns.Add("Date and Time"); 92 | list1.Columns.Add("Camera"); 93 | list1.Columns.Add("Detections"); 94 | list1.Columns.Add("Positions"); 95 | list1.Columns.Add("✓"); 96 | 97 | //set left list column width segmentation 98 | list1.Columns[0].Width = list1.Width * 0 / 100; //filename 99 | list1.Columns[1].Width = list1.Width * 47 / 100; //date 100 | list1.Columns[2].Width = list1.Width * 43 / 100; //cam name 101 | list1.Columns[3].Width = list1.Width * 0 / 100; //obj and confidences 102 | list1.Columns[4].Width = list1.Width * 0 / 100; // object positions of all detected objects separated by ";" 103 | list1.Columns[5].Width = list1.Width * 10 / 100; //checkmark if something relevant was detected or not 104 | list1.FullRowSelect = true; //make all columns clickable 105 | 106 | //check if history.csv exists, if not then create it 107 | if (!System.IO.File.Exists(@"cameras/history.csv")) 108 | { 109 | Log("ATTENTION: Creating database cameras/history.csv ."); 110 | try 111 | { 112 | using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "cameras/history.csv")) 113 | { 114 | sw.WriteLine("filename|date and time|camera|detections|positions of detections|success"); 115 | } 116 | } 117 | catch 118 | { 119 | lbl_errors.Text = "Can't create cameras/history.csv database!"; 120 | } 121 | 122 | } 123 | 124 | 125 | //this method is slow if the database is large, so it's usually only called on startup. During runtime, DeleteListImage() is used to remove obsolete images from the history list 126 | CleanCSVList(); 127 | 128 | //load entries from history.csv into history ListView 129 | //LoadFromCSV(); not neccessary because below, comboBox_filter_camera.SelectedIndex will call LoadFromCSV() 130 | 131 | splitContainer1.Panel2Collapsed = true; //collapse filter panel under left list 132 | comboBox_filter_camera.Items.Add("All Cameras"); //add "all cameras" entry in filter dropdown combobox 133 | comboBox_filter_camera.SelectedIndex = comboBox_filter_camera.FindStringExact("All Cameras"); //select all cameras entry 134 | 135 | 136 | //configure fswatcher to checks input_path for new images, images deleted and renamed images 137 | try 138 | { 139 | watcher.Path = input_path; 140 | watcher.Filter = "*.jpg"; 141 | 142 | //fswatcher events 143 | watcher.Created += new FileSystemEventHandler(OnCreatedAsync); 144 | watcher.Renamed += new RenamedEventHandler(OnRenamed); 145 | watcher.Deleted += new FileSystemEventHandler(OnDeleted); 146 | 147 | //enable fswatcher 148 | watcher.EnableRaisingEvents = true; 149 | } 150 | catch 151 | { 152 | if (input_path == "") 153 | { 154 | Log("ATTENTION: No input folder defined."); 155 | } 156 | else 157 | { 158 | Log($"ERROR: Can't access input folder '{input_path}'."); 159 | } 160 | 161 | } 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | //--------------------------------------------------------------------------- 170 | //SETTINGS TAB 171 | 172 | //fill settings tab with stored settings 173 | tbInput.Text = input_path; 174 | tbDeepstackUrl.Text = deepstack_url; 175 | tb_telegram_chatid.Text = telegram_chatid; 176 | tb_telegram_token.Text = telegram_token; 177 | cb_log.Checked = log_everything; 178 | cb_send_errors.Checked = send_errors; 179 | 180 | //--------------------------------------------------------------------------- 181 | //STATS TAB 182 | comboBox1.Items.Add("All Cameras"); //add all cameras stats entry 183 | comboBox1.SelectedIndex = comboBox1.FindStringExact("All Cameras"); //select all cameras entry 184 | 185 | 186 | this.Opacity = 1; 187 | 188 | Log("APP START complete."); 189 | } 190 | 191 | 192 | //---------------------------------------------------------------------------------------------------------- 193 | //CORE 194 | //---------------------------------------------------------------------------------------------------------- 195 | 196 | //analyze image with AI 197 | public async Task DetectObjects(string image_path) 198 | { 199 | 200 | string error = ""; //if code fails at some point, the last text of the error string will be posted in the log 201 | Log(""); 202 | Log($"Starting analysis of {image_path}"); 203 | 204 | var fullDeepstackUrl = ""; 205 | //allows both "http://ip:port" and "ip:port" 206 | if (!deepstack_url.Contains("http://")) //"ip:port" 207 | { 208 | fullDeepstackUrl = "http://" + deepstack_url + "/v1/vision/detection"; 209 | } 210 | else //"http://ip:port" 211 | { 212 | fullDeepstackUrl = deepstack_url + "/v1/vision/detection"; 213 | } 214 | 215 | 216 | // check if camera is still in the first half of the cooldown. If yes, don't analyze to minimize cpu load. 217 | 218 | string fileprefix = Path.GetFileNameWithoutExtension(image_path).Split('.')[0]; //get prefix of inputted file 219 | int index = CameraList.FindIndex(x => x.prefix == fileprefix); //get index of camera with same prefix, is =-1 if no camera has the same prefix 220 | 221 | //only analyze if 50% of the cameras cooldown time since last detection has passed 222 | if (index == -1 || (DateTime.Now - CameraList[index].last_trigger_time).TotalMinutes >= (CameraList[index].cooldown_time / 2)) //it's important that the condition index == 1 comes first, because if index is -1 and the second condition is checked, it will try to acces the CameraList at position -1 => the program cr 223 | { 224 | var request = new MultipartFormDataContent(); 225 | for (int attempts = 1; attempts < 10; attempts++) //retry if file is in use by another process. 226 | { 227 | try 228 | { 229 | error = "loading image failed"; 230 | using (var image_data = System.IO.File.OpenRead(image_path)) 231 | { 232 | Log("(1/6) Uploading image to DeepQuestAI Server"); 233 | error = $"Can't reach DeepQuestAI Server at {fullDeepstackUrl}."; 234 | request.Add(new StreamContent(image_data), "image", Path.GetFileName(image_path)); 235 | var output = await client.PostAsync(fullDeepstackUrl, request); 236 | Log("(2/6) Waiting for results"); 237 | var jsonString = await output.Content.ReadAsStringAsync(); 238 | Response response = JsonConvert.DeserializeObject(jsonString); 239 | 240 | Log("(3/6) Processing results:"); 241 | error = $"Failure in AI Tool processing the image."; 242 | 243 | //print every detected object with the according confidence-level 244 | string outputtext = " Detected objects:"; 245 | 246 | foreach (var user in response.predictions) 247 | { 248 | outputtext += $"{user.label.ToString()} ({Math.Round((user.confidence * 100), 2).ToString() }%), "; 249 | } 250 | Log(outputtext); 251 | 252 | if (response.success == true) 253 | { 254 | //if there is no camera with the same prefix 255 | if (index == -1) 256 | { 257 | Log(" No camera with the same prefix found: " + fileprefix); 258 | //check if there is a default camera which accepts any prefix, select it 259 | if (CameraList.Exists(x => x.prefix == "")) 260 | { 261 | index = CameraList.FindIndex(x => x.prefix == ""); 262 | Log("( Found a default camera."); 263 | } 264 | else 265 | { 266 | Log("WARNING: No default camera found. Aborting."); 267 | } 268 | } 269 | 270 | //index == -1 now means that no camera has the same prefix and no default camera exists. The alert therefore won't be used. 271 | 272 | 273 | //if a camera finally is associated with the inputted alert image 274 | if (index != -1) 275 | { 276 | 277 | //if camera is enabled 278 | if (CameraList[index].enabled == true) 279 | { 280 | 281 | //if something was detected 282 | if (response.predictions.Length > 0) 283 | { 284 | List objects = new List(); //list that will be filled with all objects that were detected and are triggering_objects for the camera 285 | List objects_confidence = new List(); //list containing ai confidence value of object at same position in List objects 286 | List objects_position = new List(); //list containing object positions (xmin, ymin, xmax, ymax) 287 | 288 | List irrelevant_objects = new List(); //list that will be filled with all irrelevant objects 289 | List irrelevant_objects_confidence = new List(); //list containing ai confidence value of irrelevant object at same position in List objects 290 | List irrelevant_objects_position = new List(); //list containing irrelevant object positions (xmin, ymin, xmax, ymax) 291 | 292 | 293 | int masked_counter = 0; //this value is incremented if an object is in a masked area 294 | int threshold_counter = 0; // this value is incremented if an object does not satisfy the confidence limit requirements 295 | int irrelevant_counter = 0; // this value is incremented if an irrelevant (but not masked or out of range) object is detected 296 | 297 | Log("(4/6) Checking if detected object is relevant and within confidence limits:"); 298 | //add all triggering_objects of the specific camera into a list and the correlating confidence levels into a second list 299 | foreach (var user in response.predictions) 300 | { 301 | Log($" {user.label.ToString()} ({Math.Round((user.confidence * 100), 2).ToString() }%):"); 302 | 303 | using (var img = new Bitmap(image_path)) 304 | { 305 | bool irrelevant_object = false; 306 | 307 | //if object detected is one of the objects that is relevant 308 | if (CameraList[index].triggering_objects_as_string.Contains(user.label)) 309 | { 310 | // -> OBJECT IS RELEVANT 311 | 312 | //if confidence limits are satisfied 313 | if (user.confidence * 100 >= CameraList[index].threshold_lower && user.confidence * 100 <= CameraList[index].threshold_upper) 314 | { 315 | // -> OBJECT IS WITHIN CONFIDENCE LIMITS 316 | 317 | //only if the object is outside of the masked area 318 | if (Outsidemask(CameraList[index].name, user.x_min, user.x_max, user.y_min, user.y_max, img.Width, img.Height)) 319 | { 320 | // -> OBJECT IS OUTSIDE OF MASKED AREAS 321 | 322 | objects.Add(user.label); 323 | objects_confidence.Add(user.confidence); 324 | string position = $"{user.x_min},{user.y_min},{user.x_max},{user.y_max}"; 325 | objects_position.Add(position); 326 | Log($" { user.label.ToString()} ({ Math.Round((user.confidence * 100), 2).ToString() }%) confirmed."); 327 | } 328 | else //if the object is in a masked area 329 | { 330 | masked_counter++; 331 | irrelevant_object = true; 332 | } 333 | } 334 | else //if confidence limits are not satisfied 335 | { 336 | threshold_counter++; 337 | irrelevant_object = true; 338 | } 339 | } 340 | else //if object is not relevant 341 | { 342 | irrelevant_counter++; 343 | irrelevant_object = true; 344 | } 345 | 346 | if (irrelevant_object == true) 347 | { 348 | irrelevant_objects.Add(user.label); 349 | irrelevant_objects_confidence.Add(user.confidence); 350 | string position = $"{user.x_min},{user.y_min},{user.x_max},{user.y_max}"; 351 | irrelevant_objects_position.Add(position); 352 | Log($" { user.label.ToString()} ({ Math.Round((user.confidence * 100), 2).ToString() }%) is irrelevant."); 353 | } 354 | } 355 | 356 | } 357 | 358 | //if one or more objects were detected, that are 1. relevant, 2. within confidence limits and 3. outside of masked areas 359 | if (objects.Count() > 0) 360 | { 361 | //store these last detections for the specific camera 362 | CameraList[index].last_detections = objects; 363 | CameraList[index].last_confidences = objects_confidence; 364 | CameraList[index].last_positions = objects_position; 365 | 366 | 367 | //create summary string for this detection 368 | StringBuilder detectionsTextSb = new StringBuilder(); 369 | for (int i = 0; i < objects.Count(); i++) 370 | { 371 | detectionsTextSb.Append(String.Format("{0} ({1}%) | ", objects[i], Math.Round((objects_confidence[i] * 100), 2))); 372 | } 373 | if (detectionsTextSb.Length >= 3) 374 | { 375 | detectionsTextSb.Remove(detectionsTextSb.Length - 3, 3); 376 | } 377 | CameraList[index].last_detections_summary = detectionsTextSb.ToString(); 378 | Log("The summary:" + CameraList[index].last_detections_summary); 379 | 380 | 381 | //RELEVANT ALERT 382 | Log("(5/6) Performing alert actions:"); 383 | await Trigger(index, image_path); //make TRIGGER 384 | CameraList[index].IncrementAlerts(); //stats update 385 | Log($"(6/6) SUCCESS."); 386 | 387 | 388 | 389 | 390 | 391 | //create text string objects and confidences 392 | string objects_and_confidences = ""; 393 | string object_positions_as_string = ""; 394 | for (int i = 0; i < objects.Count; i++) 395 | { 396 | objects_and_confidences += $"{objects[i]} ({Math.Round((objects_confidence[i] * 100), 0)}%); "; 397 | object_positions_as_string += $"{objects_position[i]};"; 398 | } 399 | 400 | //add to history list 401 | Log("Adding detection to history list."); 402 | CreateListItem(Path.GetFileName(image_path), DateTime.Now.ToString("dd.MM.yy, HH:mm:ss"), CameraList[index].name, objects_and_confidences, object_positions_as_string); 403 | 404 | } 405 | //if no object fulfills all 3 requirements but there are other objects: 406 | else if (irrelevant_objects.Count() > 0) 407 | { 408 | //IRRELEVANT ALERT 409 | 410 | 411 | CameraList[index].IncrementIrrelevantAlerts(); //stats update 412 | Log($"(6/6) Camera {CameraList[index].name} caused an irrelevant alert."); 413 | Log("Adding irrelevant detection to history list."); 414 | 415 | //retrieve confidences and positions 416 | string objects_and_confidences = ""; 417 | string object_positions_as_string = ""; 418 | for (int i = 0; i < irrelevant_objects.Count; i++) 419 | { 420 | objects_and_confidences += $"{irrelevant_objects[i]} ({Math.Round((irrelevant_objects_confidence[i] * 100), 0)}%); "; 421 | object_positions_as_string += $"{irrelevant_objects_position[i]};"; 422 | } 423 | 424 | //string text contains what is written in the log and in the history list 425 | string text = ""; 426 | if (masked_counter > 0)//if masked objects, add them 427 | { 428 | text += $"{masked_counter}x masked; "; 429 | } 430 | if (threshold_counter > 0)//if objects out of confidence range, add them 431 | { 432 | text += $"{threshold_counter}x not in confidence range; "; 433 | } 434 | if (irrelevant_counter > 0) //if other irrelevant objects, add them 435 | { 436 | text += $"{irrelevant_counter}x irrelevant; "; 437 | } 438 | 439 | if (text != "") //remove last ";" 440 | { 441 | text = text.Remove(text.Length - 2); 442 | } 443 | 444 | Log($"{text}, so it's an irrelevant alert."); 445 | //add to history list 446 | CreateListItem(Path.GetFileName(image_path), DateTime.Now.ToString("dd.MM.yy, HH:mm:ss"), CameraList[index].name, $"{text} : {objects_and_confidences}", object_positions_as_string); 447 | } 448 | } 449 | //if no object was detected 450 | else if (response.predictions.Length == 0) 451 | { 452 | // FALSE ALERT 453 | 454 | CameraList[index].IncrementFalseAlerts(); //stats update 455 | Log($"(6/6) Camera {CameraList[index].name} caused a false alert, nothing detected."); 456 | 457 | //add to history list 458 | Log("Adding false to history list."); 459 | CreateListItem(Path.GetFileName(image_path), DateTime.Now.ToString("dd.MM.yy, HH:mm:ss"), CameraList[index].name, "false alert", ""); 460 | } 461 | } 462 | 463 | //if camera is disabled. 464 | else if (CameraList[index].enabled == false) 465 | { 466 | Log("(6/6) Selected camera is disabled."); 467 | } 468 | 469 | } 470 | 471 | } 472 | else if (response.success == false) //if nothing was detected 473 | { 474 | Log("ERROR: no response from AI Server"); 475 | } 476 | } 477 | 478 | //load updated camera stats info in camera tab if a camera is selected 479 | MethodInvoker LabelUpdate = delegate 480 | { 481 | if (list2.SelectedItems.Count > 0) 482 | { 483 | //load only stats from Camera.cs object 484 | 485 | //all camera objects are stored in the list CameraList, so firstly the position (stored in the second column for each entry) is gathered 486 | int i = CameraList.FindIndex(x => x.name == list2.SelectedItems[0].Text); 487 | 488 | //load cameras stats 489 | string stats = $"Alerts: {CameraList[i].stats_alerts.ToString()} | Irrelevant Alerts: {CameraList[i].stats_irrelevant_alerts.ToString()} | False Alerts: {CameraList[i].stats_false_alerts.ToString()}"; 490 | lbl_camstats.Text = stats; 491 | } 492 | 493 | 494 | }; 495 | Invoke(LabelUpdate); 496 | break; //end retries if code was successful 497 | } 498 | catch (Exception ex) 499 | { 500 | Log($"{ex.GetType().ToString()} | {ex.Message.ToString()} (code: {ex.HResult} )"); 501 | 502 | if (error == "loading image failed") //this was a file exception error - retry file access 503 | { 504 | if (attempts != 9) //failure at attempt 1-8 505 | { 506 | Log($"Could not access file - will retry after {attempts * retry_delay} ms delay"); 507 | } 508 | else //last attempt failed 509 | { 510 | Log($"ERROR: Could not access image '{image_path}'."); 511 | } 512 | } 513 | else //all other exceptions 514 | { 515 | Log($"ERROR: Processing the following image '{image_path}' failed. {error}"); 516 | //upload the alert image which could not be analyzed to Telegram 517 | if (send_errors == true) 518 | { 519 | await TelegramUpload(image_path); 520 | } 521 | break; //end retries - this was not a file access error 522 | } 523 | 524 | } 525 | System.Threading.Thread.Sleep(retry_delay * attempts); 526 | Log($"Retrying image processing - retry {attempts}"); 527 | } 528 | } 529 | 530 | /* 531 | try 532 | { 533 | System.IO.File.Delete(image_path); 534 | } 535 | catch 536 | { 537 | Console.WriteLine($"ERROR: Could not delete {image_path} ."); 538 | }*/ 539 | 540 | 541 | } 542 | 543 | //call trigger urls 544 | public void CallTriggerURLs(string[] trigger_urls) 545 | { 546 | 547 | var client = new WebClient(); 548 | foreach (string x in trigger_urls) 549 | { 550 | try 551 | { 552 | Log($" trigger url: {x}"); 553 | var content = client.DownloadString(x); 554 | } 555 | catch (Exception ex) 556 | { 557 | Log(ex.Message); 558 | Log($"ERROR: Could not trigger URL '{x}', please check if '{x}' is correct and reachable."); 559 | } 560 | 561 | } 562 | 563 | if (trigger_urls.Length > 1) 564 | { 565 | Log($" -> {trigger_urls.Length} trigger URLs called."); 566 | } 567 | else 568 | { 569 | Log(" -> Trigger URL called."); 570 | } 571 | } 572 | 573 | //send image to Telegram 574 | public async Task TelegramUpload(string image_path) 575 | { 576 | if (telegram_chatid != "" && telegram_token != "") 577 | { 578 | //telegram upload sometimes fails 579 | try 580 | { 581 | using (var image_telegram = System.IO.File.OpenRead(image_path)) 582 | { 583 | var bot = new TelegramBotClient(telegram_token); 584 | 585 | //upload image to Telegram servers and send to first chat 586 | Log($" uploading image to chat \"{telegram_chatids[0]}\""); 587 | var message = await bot.SendPhotoAsync(telegram_chatids[0], new InputOnlineFile(image_telegram, "image.jpg")); 588 | string file_id = message.Photo[0].FileId; //get file_id of uploaded image 589 | 590 | //share uploaded image with all remaining telegram chats (if multiple chat_ids given) using file_id 591 | foreach (string chatid in telegram_chatids.Skip(1)) 592 | { 593 | Log($" uploading image to chat \"{chatid}\""); 594 | await bot.SendPhotoAsync(chatid, file_id); 595 | } 596 | } 597 | } 598 | catch 599 | { 600 | Log($"ERROR: Could not upload image {image_path} to Telegram."); 601 | //store image that caused an error in ./errors/ 602 | if (!Directory.Exists("./errors/")) //if folder does not exist, create the folder 603 | { 604 | //create folder 605 | DirectoryInfo di = Directory.CreateDirectory("./errors"); 606 | Log("./errors/" + " dir created."); 607 | } 608 | //save error image 609 | using (var image = SixLabors.ImageSharp.Image.Load(image_path)) 610 | { 611 | image.Save("./errors/" + "TELEGRAM-ERROR-" + Path.GetFileName(image_path) + ".jpg"); 612 | } 613 | } 614 | 615 | } 616 | } 617 | 618 | //send text to Telegram 619 | public async Task TelegramText(string text) 620 | { 621 | if (telegram_chatid != "" && telegram_token != "") 622 | { 623 | //telegram upload sometimes fails 624 | try 625 | { 626 | var bot = new Telegram.Bot.TelegramBotClient(telegram_token); 627 | foreach (string chatid in telegram_chatids) 628 | { 629 | await bot.SendTextMessageAsync(chatid, text); 630 | } 631 | 632 | } 633 | catch 634 | { 635 | if (send_errors == true && text.Contains("ERROR") || text.Contains("WARNING")) //if Error message originating from Log() methods can't be uploaded 636 | { 637 | send_errors = false; //shortly disable send_errors to ensure that the Log() does not try to send the 'Telegram upload failed' message via Telegram again (causing a loop) 638 | Log($"ERROR: Could not send text \"{text}\" to Telegram."); 639 | send_errors = true; 640 | 641 | //inform on main tab that Telegram upload failed 642 | MethodInvoker LabelUpdate = delegate { lbl_errors.Text = "Can't upload error message to Telegram!"; }; 643 | Invoke(LabelUpdate); 644 | } 645 | else 646 | { 647 | Log($"ERROR: Could not send text \"{text}\" to Telegram."); 648 | } 649 | } 650 | 651 | } 652 | } 653 | 654 | //trigger actions 655 | public async Task Trigger(int index, string image_path) 656 | { 657 | //only trigger if cameras cooldown time since last detection has passed 658 | if ((DateTime.Now - CameraList[index].last_trigger_time).TotalMinutes >= CameraList[index].cooldown_time) 659 | { 660 | //call trigger urls 661 | if (CameraList[index].trigger_urls.Length > 0) 662 | { 663 | //replace url paramters with according values 664 | string[] urls = new string[CameraList[index].trigger_urls.Count()]; 665 | int c = 0; 666 | //call urls 667 | foreach (string url in CameraList[index].trigger_urls) 668 | { 669 | try 670 | { 671 | urls[c] = url.Replace("[camera]", CameraList[index].name) 672 | .Replace("[detection]", CameraList[index].last_detections.ElementAt(0)) //only gives first detection (maybe not most relevant one) 673 | .Replace("[position]", CameraList[index].last_positions.ElementAt(0)) 674 | .Replace("[confidence]", CameraList[index].last_confidences.ElementAt(0).ToString()) 675 | .Replace("[detections]", string.Join(",", CameraList[index].last_detections)) 676 | .Replace("[confidences]", string.Join(",", CameraList[index].last_confidences.ToString())) 677 | .Replace("[imagepath]", image_path) //gives the full path of the image that caused the trigger 678 | .Replace("[imagefilename]", Path.GetFileName(image_path)) //gives the image name of the image that caused the trigger 679 | .Replace("[summary]", Uri.EscapeUriString(CameraList[index].last_detections_summary)); //summary text including all detections and confidences, p.e."person (91,53%)" 680 | } 681 | catch (Exception ex) 682 | { 683 | Log($"{ex.GetType().ToString()} | {ex.Message.ToString()} (code: {ex.HResult} )"); 684 | } 685 | 686 | c++; 687 | } 688 | 689 | CallTriggerURLs(urls); 690 | } 691 | 692 | 693 | //upload to telegram 694 | if (CameraList[index].telegram_enabled) 695 | { 696 | Log(" Uploading image to Telegram..."); 697 | await TelegramUpload(image_path); 698 | Log(" -> Sent image to Telegram."); 699 | } 700 | } 701 | else 702 | { 703 | //log that nothing was done 704 | Log($" Camera {CameraList[index].name} is still in cooldown. Trigger URL wasn't called and no image will be uploaded to Telegram."); 705 | } 706 | 707 | CameraList[index].last_trigger_time = DateTime.Now; //reset cooldown time every time an image contains something, even if no trigger was called (still in cooldown time) 708 | 709 | Task ignoredAwaitableResult = this.LastTriggerInfo(index, CameraList[index].cooldown_time); //write info to label 710 | 711 | } 712 | 713 | 714 | 715 | //check if detected object is outside the mask for the specific camera 716 | public bool Outsidemask(string cameraname, double xmin, double xmax, double ymin, double ymax, int width, int height) 717 | { 718 | Log($" Checking if object is outside privacy mask of {cameraname}:"); 719 | Log(" Loading mask file..."); 720 | try 721 | { 722 | if (System.IO.File.Exists("./cameras/" + cameraname + ".png")) //only check if mask image exists 723 | { 724 | //load mask file (in the image all places that have color (transparency > 9 [0-255 scale]) are masked) 725 | using (var mask_img = new Bitmap($"./cameras/{cameraname}.png")) 726 | { 727 | //if any coordinates of the object are outside of the mask image, th mask image must be too small. 728 | if (mask_img.Width != width || mask_img.Height != height) 729 | { 730 | Log($"ERROR: The resolution of the mask './camera/{cameraname}.png' does not equal the resolution of the processed image. Skipping privacy mask feature. Image: {width}x{height}, Mask: {mask_img.Width}x{mask_img.Height}"); 731 | return true; 732 | } 733 | 734 | Log(" Checking if the object is in a masked area..."); 735 | 736 | //relative x and y locations of the 9 detection points 737 | double[] x_factor = new double[] { 0.25, 0.5, 0.75, 0.25, 0.5, 0.75, 0.25, 0.5, 0.75 }; 738 | double[] y_factor = new double[] { 0.25, 0.25, 0.25, 0.5, 0.5, 0.5, 0.75, 0.75, 0.75 }; 739 | 740 | int result = 0; //counts how many of the 9 points are outside of masked area(s) 741 | 742 | //check the transparency of the mask image in all 9 detection points 743 | for (int i = 0; i < 9; i++) 744 | { 745 | //get image point coordinates (and converting double to int) 746 | int x = (int)(xmin + (xmax - xmin) * x_factor[i]); 747 | int y = (int)(ymin + (ymax - ymin) * y_factor[i]); 748 | 749 | // Get the color of the pixel 750 | Color pixelColor = mask_img.GetPixel(x, y); 751 | 752 | //if the pixel is transparent (A refers to the alpha channel), the point is outside of masked area(s) 753 | if (pixelColor.A < 10) 754 | { 755 | result++; 756 | } 757 | } 758 | 759 | Log($" { result.ToString() } of 9 detection points are outside of masked areas."); //print how many of the 9 detection points are outside of masked areas. 760 | 761 | if (result > 4) //if 5 or more of the 9 detection points are outside of masked areas, the majority of the object is outside of masked area(s) 762 | { 763 | Log(" ->The object is OUTSIDE of masked area(s)."); 764 | return true; 765 | } 766 | else //if 4 or less of 9 detection points are outside, then 5 or more points are in masked areas and the majority of the object is so too 767 | { 768 | Log(" ->The object is INSIDE a masked area."); 769 | return false; 770 | } 771 | 772 | } 773 | } 774 | else //if mask image does not exist, object is outside the non-existing masked area 775 | { 776 | Log(" ->Camera has no mask, the object is OUTSIDE of the masked area."); 777 | return true; 778 | } 779 | 780 | } 781 | catch 782 | { 783 | Log($"ERROR while loading the mask file ./cameras/{cameraname}.png."); 784 | return true; 785 | } 786 | 787 | } 788 | 789 | //save how many times an error happened 790 | public void IncrementErrorCounter() 791 | { 792 | errors++; 793 | MethodInvoker LabelUpdate = delegate 794 | { 795 | lbl_errors.Show(); 796 | lbl_errors.Text = $"{errors.ToString()} error(s) occured. Click to open Log."; //update error counter label 797 | }; 798 | Invoke(LabelUpdate); 799 | } 800 | 801 | //add text to log 802 | public async void Log(string text) 803 | { 804 | 805 | //if log everything is disabled and the text is neighter an ERROR, nor a WARNING: write only to console and ABORT 806 | if (log_everything == false && !text.Contains("ERROR") && !text.Contains("WARNING")) 807 | { 808 | text += "Enabling \'Log everything\' might give more information."; 809 | Console.WriteLine($"{text}"); 810 | return; 811 | } 812 | 813 | 814 | //get current date and time 815 | 816 | string time = DateTime.Now.ToString("dd.MM.yyyy, HH:mm:ss"); 817 | 818 | if (log_everything == true) 819 | { 820 | time = DateTime.Now.ToString("dd.MM.yyyy, HH:mm:ss.fff"); 821 | } 822 | 823 | 824 | //if log file does not exist, create it 825 | if (!System.IO.File.Exists("./log.txt")) 826 | { 827 | Console.WriteLine("ATTENTION: Creating log file."); 828 | try 829 | { 830 | using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "log.txt")) 831 | { 832 | sw.WriteLine("Log format: [dd.MM.yyyy, HH:mm:ss]: Log text."); 833 | } 834 | } 835 | catch 836 | { 837 | MethodInvoker LabelUpdate = delegate { lbl_errors.Text = "Can't create log.txt file!"; }; 838 | Invoke(LabelUpdate); 839 | } 840 | 841 | } 842 | 843 | //add text to log 844 | try 845 | { 846 | using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "log.txt", append: true)) 847 | { 848 | sw.WriteLine($"[{time}]: {text}"); 849 | } 850 | } 851 | catch 852 | { 853 | MethodInvoker LabelUpdate = delegate { lbl_errors.Text = "Can't write to log.txt file!"; }; 854 | Invoke(LabelUpdate); 855 | } 856 | 857 | if (send_errors == true && text.Contains("ERROR") || text.Contains("WARNING")) 858 | { 859 | await TelegramText($"[{time}]: {text}"); //upload text to Telegram 860 | } 861 | 862 | 863 | 864 | //add log text to console 865 | Console.WriteLine($"[{time}]: {text}"); 866 | 867 | //increment error counter 868 | if (text.Contains("ERROR") || text.Contains("WARNING")) 869 | { 870 | IncrementErrorCounter(); 871 | } 872 | 873 | } 874 | 875 | //update input path for fswatcher 876 | public void UpdateFSWatcher() 877 | { 878 | try 879 | { 880 | watcher.Path = input_path; 881 | } 882 | catch 883 | { 884 | if (input_path == "") 885 | { 886 | Log("ATTENTION: No input folder defined."); 887 | } 888 | else 889 | { 890 | Log($"ERROR: Can't access input folder '{input_path}'."); 891 | } 892 | 893 | } 894 | } 895 | 896 | //---------------------------------------------------------------------------------------------------------- 897 | //GUI 898 | //---------------------------------------------------------------------------------------------------------- 899 | 900 | //minimize to tray 901 | private void Form1_Resize(object sender, EventArgs e) 902 | { 903 | if (this.WindowState == FormWindowState.Minimized) 904 | { 905 | this.Hide(); 906 | notifyIcon.Visible = true; 907 | } 908 | else 909 | { 910 | ResizeListViews(); 911 | } 912 | } 913 | 914 | //open from tray 915 | private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) 916 | { 917 | this.Show(); 918 | this.WindowState = FormWindowState.Normal; 919 | notifyIcon.Visible = false; 920 | } 921 | 922 | //open Log when clicking or error message 923 | private void lbl_errors_Click(object sender, EventArgs e) 924 | { 925 | if (System.IO.File.Exists("log.txt")) 926 | { 927 | System.Diagnostics.Process.Start("log.txt"); 928 | lbl_errors.Text = ""; 929 | } 930 | else 931 | { 932 | MessageBox.Show("log missing"); 933 | } 934 | 935 | } 936 | 937 | //adapt list views (history tab and cameras tab) to window size while considering scrollbar influence 938 | private void ResizeListViews() 939 | { 940 | //suspend layout of most complex tablelayout elements (gives a few milliseconds) 941 | tableLayoutPanel7.SuspendLayout(); 942 | tableLayoutPanel8.SuspendLayout(); 943 | tableLayoutPanel9.SuspendLayout(); 944 | 945 | //variable storing list1 effective width 946 | int width = list1.Width; 947 | 948 | //subtract vertical scrollbar width if scrollbar is shown (scrollbar is shown when there are more items(including the header row) than fit in the visible space of the list) 949 | try 950 | { 951 | if (list1.Items.Count > 0 && list1.Height <= (list1.GetItemRect(0).Height * (list1.Items.Count + 1))) 952 | { 953 | width -= SystemInformation.VerticalScrollBarWidth; 954 | } 955 | } 956 | catch 957 | { 958 | Log("ERROR in ReziseListViews(), checking if scrollbar is shown and subtracting scrollbar width failed."); 959 | } 960 | 961 | if (width > 350) // if the list is wider than 350px, aditionally show the 'detections' column and mainly grow this column 962 | { 963 | //set left list column width segmentation 964 | list1.Columns[0].Width = width * 0 / 100; //filename 965 | list1.Columns[1].Width = 120 + (width - 350) * 25 / 1000; //date 966 | list1.Columns[2].Width = 120 + (width - 350) * 25 / 1000; //cam name 967 | list1.Columns[3].Width = 80 + (width - 350) * 95 / 100; //obj and confidences 968 | list1.Columns[4].Width = width * 0 / 100; // object positions of all detected objects separated by ";" 969 | list1.Columns[5].Width = 30; //checkmark if something relevant detected or not 970 | 971 | } 972 | else //if the form is smaller than 350px in width, don't show the detections column 973 | { 974 | //set left list column width segmentation 975 | list1.Columns[0].Width = width * 0 / 100; //filename 976 | list1.Columns[1].Width = width * 47 / 100; //date 977 | list1.Columns[2].Width = width * 43 / 100; //cam name 978 | list1.Columns[3].Width = width * 0 / 100; //obj and confidences 979 | list1.Columns[4].Width = width * 0 / 100; // object positions of all detected objects separated by ";" 980 | list1.Columns[5].Width = width * 10 / 100; //checkmark if something relevant detected or not 981 | } 982 | 983 | list2.Columns[0].Width = list2.Width - 4; //resize camera list column 984 | 985 | //resume layout again 986 | tableLayoutPanel7.ResumeLayout(); 987 | tableLayoutPanel8.ResumeLayout(); 988 | tableLayoutPanel9.ResumeLayout(); 989 | } 990 | 991 | //add last trigger time to label on Overview page 992 | private async Task LastTriggerInfo(int index, double minutes) 993 | { 994 | string text1 = $"{CameraList[index].name} last triggered at {CameraList[index].last_trigger_time}. Sleeping for {minutes / 2} minutes."; //write last trigger time to label on Overview page 995 | lbl_info.Text = text1; 996 | 997 | int time = 30 * Convert.ToInt32(1000 * minutes); 998 | await Task.Delay(time); // wait while the analysis is sleeping for this camera 999 | if (lbl_info.Text == text1) 1000 | { 1001 | lbl_info.Text = $"{CameraList[index].name} last triggered at {CameraList[index].last_trigger_time}."; //Remove "sleeping for ..." 1002 | } 1003 | } 1004 | 1005 | 1006 | //EVENTS: 1007 | 1008 | //event: mouse click on tab control 1009 | private void tabControl1_MouseDown(object sender, MouseEventArgs e) 1010 | { 1011 | ResizeListViews(); 1012 | } 1013 | 1014 | //event: another tab selected (Only load certain things in tabs if they are actually open) 1015 | private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) 1016 | { 1017 | if (tabControl1.SelectedIndex == 1) 1018 | { 1019 | UpdatePieChart(); UpdateTimeline(); UpdateConfidenceChart(); 1020 | } 1021 | else if (tabControl1.SelectedIndex == 2) 1022 | { 1023 | //CleanCSVList(); //removed to load the history list faster 1024 | } 1025 | } 1026 | 1027 | 1028 | //---------------------------------------------------------------------------------------------------------- 1029 | //STATS TAB 1030 | //---------------------------------------------------------------------------------------------------------- 1031 | 1032 | //other camera in combobox selected, display according PieChart 1033 | private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e) 1034 | { 1035 | if (tabControl1.SelectedIndex == 1) 1036 | { 1037 | 1038 | UpdatePieChart(); UpdateTimeline(); UpdateConfidenceChart(); 1039 | } 1040 | } 1041 | 1042 | //update pie chart 1043 | public void UpdatePieChart() 1044 | { 1045 | int alerts = 0; 1046 | int irrelevantalerts = 0; 1047 | int falsealerts = 0; 1048 | 1049 | if (comboBox1.Text == "All Cameras") 1050 | { 1051 | foreach (Camera cam in CameraList) 1052 | { 1053 | alerts += cam.stats_alerts; 1054 | irrelevantalerts += cam.stats_irrelevant_alerts; 1055 | falsealerts += cam.stats_false_alerts; 1056 | } 1057 | } 1058 | else 1059 | { 1060 | int i = CameraList.FindIndex(x => x.name == comboBox1.Text.Substring(3)); 1061 | alerts = CameraList[i].stats_alerts; 1062 | irrelevantalerts = CameraList[i].stats_irrelevant_alerts; 1063 | falsealerts = CameraList[i].stats_false_alerts; 1064 | } 1065 | 1066 | chart1.Series[0].Points.Clear(); 1067 | 1068 | chart1.Series[0].LegendText = "#VALY #VALX"; 1069 | chart1.Series[0]["PieLabelStyle"] = "Disabled"; 1070 | 1071 | int index = -1; 1072 | 1073 | //show Alerts label 1074 | index = chart1.Series[0].Points.AddXY("Alerts", alerts); 1075 | chart1.Series[0].Points[index].Color = Color.Green; 1076 | 1077 | //show irrelevant Alerts label 1078 | index = chart1.Series[0].Points.AddXY("irrelevant Alerts", irrelevantalerts); 1079 | chart1.Series[0].Points[index].Color = Color.Orange; 1080 | 1081 | //show false Alerts label 1082 | index = chart1.Series[0].Points.AddXY("false Alerts", falsealerts); 1083 | chart1.Series[0].Points[index].Color = Color.OrangeRed; 1084 | } 1085 | 1086 | //update timeline 1087 | public void UpdateTimeline() 1088 | { 1089 | Log("Loading time line from cameras/history.csv ..."); 1090 | 1091 | //clear previous values 1092 | timeline.Series[0].Points.Clear(); 1093 | timeline.Series[1].Points.Clear(); 1094 | timeline.Series[2].Points.Clear(); 1095 | timeline.Series[3].Points.Clear(); 1096 | 1097 | List result = new List(); //List that later on will be containing all lines of the csv file 1098 | 1099 | if (comboBox1.Text == "All Cameras") //all cameras selected 1100 | { 1101 | //load all lines except the first line 1102 | foreach (string line in System.IO.File.ReadAllLines(@"cameras/history.csv").Skip(1)) 1103 | { 1104 | result.Add(line); 1105 | } 1106 | } 1107 | else //camera selection 1108 | { 1109 | string cameraname = comboBox1.Text.Substring(3); 1110 | 1111 | //load all lines from the history.csv except the first line into List (the first line is the table heading and not an alert entry) 1112 | foreach (string line in System.IO.File.ReadAllLines(@"cameras/history.csv").Skip(1)) 1113 | { 1114 | if (line.Split('|')[2] == cameraname) 1115 | { 1116 | result.Add(line); 1117 | } 1118 | } 1119 | } 1120 | 1121 | //every int represents the number of ai calls in successive half hours (p.e. relevant[0] is 0:00-0:30 o'clock, relevant[1] is 0:30-1:00 o'clock) 1122 | int[] all = new int[48]; 1123 | int[] falses = new int[48]; 1124 | int[] irrelevant = new int[48]; 1125 | int[] relevant = new int[48]; 1126 | 1127 | //fill arrays with amount of calls/half hour 1128 | foreach (var val in result) 1129 | { //example of time column entry: 23.08.19, 18:31:09 1130 | //get hour 1131 | string hourstring = val.Split('|')[1].Split(',')[1].Split(':')[0]; 1132 | int hour; 1133 | Int32.TryParse(hourstring, out hour); 1134 | 1135 | //get minute 1136 | string minutestring = val.Split('|')[1].Split(',')[1].Split(':')[1]; 1137 | int minute; 1138 | Int32.TryParse(minutestring, out minute); 1139 | 1140 | int halfhour; //stores the half hour in which the alert occured 1141 | 1142 | //add +1 to counter for corresponding half-hour 1143 | if (minute > 30) //if alert occured after half o clock 1144 | { 1145 | halfhour = hour * 2 + 1; 1146 | } 1147 | else //if alert occured before half o clock 1148 | { 1149 | halfhour = hour * 2; 1150 | } 1151 | 1152 | //if detection was successful 1153 | if (val.Split('|')[5] == "true") 1154 | { 1155 | relevant[halfhour]++; 1156 | } 1157 | //if it was a false alert 1158 | else if (val.Split('|')[3] == "false alert") 1159 | { 1160 | falses[halfhour]++; 1161 | } 1162 | //if something irrelevant was detected 1163 | else 1164 | { 1165 | irrelevant[halfhour]++; 1166 | } 1167 | 1168 | all[halfhour]++; 1169 | } 1170 | 1171 | //add to graph "all": 1172 | 1173 | /*the graph will have a gap at the end and at the beginning if we don'f specify a value 1174 | * with an x value outside the visible area at the end and before the first visible point. 1175 | * So the first point is at -0.25 and has the value of the last visible point and the 1176 | * last point is at 24.25 and has the value of the first visible point. */ 1177 | 1178 | timeline.Series[0].Points.AddXY(-0.25, all[47]); // beginning point with value of last visible point 1179 | 1180 | //and now add all visible points 1181 | double x = 0.25; 1182 | foreach (int halfhour in all) 1183 | { 1184 | int index = timeline.Series[0].Points.AddXY(x, halfhour); 1185 | x = x + 0.5; 1186 | } 1187 | 1188 | timeline.Series[0].Points.AddXY(24.25, all[0]); // finally add last point with value of first visible point 1189 | 1190 | //add to graph "falses": 1191 | 1192 | timeline.Series[1].Points.AddXY(-0.25, falses[47]); // beginning point with value of last visible point 1193 | //and now add all visible points 1194 | x = 0.25; 1195 | foreach (int halfhour in falses) 1196 | { 1197 | int index = timeline.Series[1].Points.AddXY(x, halfhour); 1198 | x = x + 0.5; 1199 | } 1200 | timeline.Series[1].Points.AddXY(24.25, falses[0]); // finally add last point with value of first visible point 1201 | 1202 | //add to graph "irrelevant": 1203 | 1204 | timeline.Series[2].Points.AddXY(-0.25, irrelevant[47]); // beginning point with value of last visible point 1205 | //and now add all visible points 1206 | x = 0.25; 1207 | foreach (int halfhour in irrelevant) 1208 | { 1209 | int index = timeline.Series[2].Points.AddXY(x, halfhour); 1210 | x = x + 0.5; 1211 | } 1212 | timeline.Series[2].Points.AddXY(24.25, irrelevant[0]); // finally add last point with value of first visible point 1213 | 1214 | //add to graph "relevant": 1215 | 1216 | timeline.Series[3].Points.AddXY(-0.25, relevant[47]); // beginning point with value of last visible point 1217 | //and now add all visible points 1218 | x = 0.25; 1219 | foreach (int halfhour in relevant) 1220 | { 1221 | int index = timeline.Series[3].Points.AddXY(x, halfhour); 1222 | x = x + 0.5; 1223 | } 1224 | timeline.Series[3].Points.AddXY(24.25, relevant[0]); // finally add last point with value of first visible point 1225 | 1226 | 1227 | } 1228 | 1229 | //update confidence_frequency chart 1230 | public void UpdateConfidenceChart() 1231 | { 1232 | Log("Loading confidence-frequency chart from cameras/history.csv ..."); 1233 | 1234 | //clear previous values 1235 | chart_confidence.Series[0].Points.Clear(); 1236 | chart_confidence.Series[1].Points.Clear(); 1237 | 1238 | List result = new List(); //List that later on will be containing all lines of the csv file 1239 | 1240 | if (comboBox1.Text == "All Cameras") //all cameras selected 1241 | { 1242 | //load all lines except the first line 1243 | foreach (string line in System.IO.File.ReadAllLines(@"cameras/history.csv").Skip(1)) 1244 | { 1245 | result.Add(line); 1246 | } 1247 | } 1248 | else //camera selection 1249 | { 1250 | string cameraname = comboBox1.Text.Substring(3); 1251 | 1252 | //load all lines from the history.csv except the first line into List (the first line is the table heading and not an alert entry) 1253 | foreach (string line in System.IO.File.ReadAllLines(@"cameras/history.csv").Skip(1)) 1254 | { 1255 | if (line.Split('|')[2] == cameraname) 1256 | { 1257 | result.Add(line); 1258 | 1259 | } 1260 | } 1261 | } 1262 | 1263 | //this array stores the Absolute frequencies of all possible confidence values (0%-100%) 1264 | int[] green_values = new int[101]; 1265 | int[] orange_values = new int[101]; 1266 | 1267 | //fill array with frequencies 1268 | foreach (var line in result) 1269 | { 1270 | //example of detections column entry: "person (41%); person (97%);" or "masked: person (41%); person (97%);" 1271 | string detections_column = line.Split('|')[3]; 1272 | if (detections_column.Contains(':')) 1273 | { 1274 | detections_column = detections_column.Split(':')[1]; 1275 | 1276 | string[] detections = detections_column.Split(';'); 1277 | 1278 | //write the confidence of every detection into the green_values string 1279 | foreach (string detection in detections) 1280 | { 1281 | if (detection.Contains('%')) 1282 | { 1283 | //example: -> "person (41%)" 1284 | Int32.TryParse(detection.Split('(')[1].Split('%')[0], out int x_value); //example: -> "41" 1285 | orange_values[x_value]++; 1286 | } 1287 | } 1288 | } 1289 | else 1290 | { 1291 | string[] detections = detections_column.Split(';'); 1292 | 1293 | //write the confidence of every detection into the green_values string 1294 | foreach (string detection in detections) 1295 | { 1296 | if (detection.Contains('%')) 1297 | { 1298 | //example: -> "person (41%)" 1299 | Int32.TryParse(detection.Split('(')[1].Split('%')[0], out int x_value); //example: -> "41" 1300 | green_values[x_value]++; 1301 | } 1302 | } 1303 | } 1304 | } 1305 | 1306 | 1307 | //write green series in chart 1308 | int i = 0; 1309 | foreach (int y_value in green_values) 1310 | { 1311 | chart_confidence.Series[1].Points.AddXY(i, y_value); 1312 | i++; 1313 | } 1314 | 1315 | //write orange series in chart 1316 | i = 0; 1317 | foreach (int y_value in orange_values) 1318 | { 1319 | chart_confidence.Series[0].Points.AddXY(i, y_value); 1320 | i++; 1321 | } 1322 | 1323 | } 1324 | 1325 | 1326 | //---------------------------------------------------------------------------------------------------------- 1327 | //HISTORY TAB 1328 | //---------------------------------------------------------------------------------------------------------- 1329 | 1330 | // load images from input_path to left list 1331 | /*public void LoadList() 1332 | { 1333 | list1.Items.Clear(); 1334 | try 1335 | { 1336 | string[] files = Directory.GetFiles(input_path, $"*.jpg"); 1337 | 1338 | foreach (string file in files) 1339 | { 1340 | 1341 | string fileName = Path.GetFileName(file); 1342 | ListViewItem item = new ListViewItem(new string[] { fileName, "content" }); 1343 | item.Tag = file; 1344 | 1345 | list1.Items.Add(item); 1346 | 1347 | } 1348 | } 1349 | catch 1350 | { 1351 | MessageBox.Show("Can't find the input directory, please check it."); 1352 | } 1353 | if (list1.Items.Count > 0) 1354 | { 1355 | list1.Items[0].Selected = true; //select first image 1356 | } 1357 | }*/ 1358 | 1359 | //show or hide the privacy mask overlay 1360 | private void showHideMask() 1361 | { 1362 | if (cb_showMask.Checked == true) //show overlay 1363 | { 1364 | Log("Show mask toggled."); 1365 | if (list1.SelectedItems.Count > 0) 1366 | { 1367 | if (System.IO.File.Exists("./cameras/" + list1.SelectedItems[0].SubItems[2].Text + ".png")) //check if privacy mask file exists 1368 | { 1369 | using (var img = new Bitmap("./cameras/" + list1.SelectedItems[0].SubItems[2].Text + ".png")) 1370 | { 1371 | pictureBox1.Image = new Bitmap(img); //load mask as overlay 1372 | } 1373 | } 1374 | else 1375 | { 1376 | pictureBox1.Image = null; //if file does not exist, empty mask overlay (from possible overlays of previous images) 1377 | } 1378 | 1379 | } 1380 | } 1381 | else //if showmask toggle-button is not checked, hide the mask overlay 1382 | { 1383 | pictureBox1.Image = null; 1384 | } 1385 | 1386 | } 1387 | 1388 | //show rectangle overlay 1389 | private void showObject(PaintEventArgs e, Color color, int _xmin, int _ymin, int _xmax, int _ymax, string text) 1390 | { 1391 | if (list1.SelectedItems.Count > 0) 1392 | { 1393 | //1. get the padding between the image and the picturebox border 1394 | 1395 | //get dimensions of the image and the picturebox 1396 | float imgWidth = pictureBox1.BackgroundImage.Width; 1397 | float imgHeight = pictureBox1.BackgroundImage.Height; 1398 | float boxWidth = pictureBox1.Width; 1399 | float boxHeight = pictureBox1.Height; 1400 | 1401 | //these variables store the padding between image border and picturebox border 1402 | int absX = 0; 1403 | int absY = 0; 1404 | 1405 | //because the sizemode of the picturebox is set to 'zoom', the image is scaled down 1406 | float scale = 1; 1407 | 1408 | 1409 | //Comparing the aspect ratio of both the control and the image itself. 1410 | if (imgWidth / imgHeight > boxWidth / boxHeight) //if the image is p.e. 16:9 and the picturebox is 4:3 1411 | { 1412 | scale = boxWidth / imgWidth; //get scale factor 1413 | absY = (int)(boxHeight - scale * imgHeight) / 2; //padding on top and below the image 1414 | } 1415 | else //if the image is p.e. 4:3 and the picturebox is widescreen 16:9 1416 | { 1417 | scale = boxHeight / imgHeight; //get scale factor 1418 | absX = (int)(boxWidth - scale * imgWidth) / 2; //padding left and right of the image 1419 | } 1420 | 1421 | //2. inputted position values are for the original image size. As the image is probably smaller in the picturebox, the positions must be adapted. 1422 | int xmin = (int)(scale * _xmin) + absX; 1423 | int xmax = (int)(scale * _xmax) + absX; 1424 | int ymin = (int)(scale * _ymin) + absY; 1425 | int ymax = (int)(scale * _ymax) + absY; 1426 | 1427 | //3. paint rectangle 1428 | System.Drawing.Rectangle rect = new System.Drawing.Rectangle(xmin, ymin, xmax - xmin, ymax - ymin); 1429 | using (Pen pen = new Pen(color, 2)) 1430 | { 1431 | e.Graphics.DrawRectangle(pen, rect); //draw rectangle 1432 | } 1433 | 1434 | //object name text below rectangle 1435 | rect = new System.Drawing.Rectangle(xmin - 1, ymax, (int)boxWidth, 1436 | (int)boxHeight); //sets bounding box for drawn text 1437 | Brush brush = new SolidBrush(color); //sets background rectangle color 1438 | System.Drawing.SizeF 1439 | size = e.Graphics.MeasureString(text, 1440 | new Font("Segoe UI Semibold", 10)); //finds size of text to draw the background rectangle 1441 | e.Graphics.FillRectangle(brush, xmin - 1, ymax, size.Width, 1442 | size.Height); //draw grey background rectangle for detection text 1443 | e.Graphics.DrawString(text, new Font("Segoe UI Semibold", 10), Brushes.Black, rect); //draw detection text 1444 | 1445 | } 1446 | } 1447 | 1448 | //load object rectangle overlays 1449 | private void pictureBox1_Paint(object sender, PaintEventArgs e) 1450 | { 1451 | if (cb_showObjects.Checked && list1.SelectedItems.Count > 0) //if checkbox button is enabled 1452 | { 1453 | Log("Loading object rectangles..."); 1454 | int countr = list1.SelectedItems[0].SubItems[4].Text.Split(';').Count(); 1455 | 1456 | Color color = new Color(); 1457 | string detections = list1.SelectedItems[0].SubItems[3].Text; 1458 | if (detections.Contains("irrelevant") || detections.Contains("masked") || detections.Contains("confidence")) 1459 | { 1460 | color = Color.Silver; 1461 | detections = detections.Split(':')[1]; //removes the "1x masked, 3x irrelevant:" before the actual detection, otherwise this would be displayed in the detection tags 1462 | } 1463 | else 1464 | { 1465 | color = Color.Red; 1466 | } 1467 | 1468 | //display a rectangle around each relevant object 1469 | for (int i = 0; i < countr - 1; i++) 1470 | { 1471 | string[] detectionsArray = detections.Split(';');//creates array of detected objects, used for adding text overlay 1472 | //load 'xmin,ymin,xmax,ymax' from third column into a string 1473 | string position = list1.SelectedItems[0].SubItems[4].Text.Split(';')[i]; 1474 | 1475 | //store xmin, ymin, xmax, ymax in separate variables 1476 | Int32.TryParse(position.Split(',')[0], out int xmin); 1477 | Int32.TryParse(position.Split(',')[1], out int ymin); 1478 | Int32.TryParse(position.Split(',')[2], out int xmax); 1479 | Int32.TryParse(position.Split(',')[3], out int ymax); 1480 | 1481 | Log($"{i} - {xmin}, {ymin}, {xmax}, {ymax}"); 1482 | 1483 | showObject(e, color, xmin, ymin, xmax, ymax, detectionsArray[i]); //call rectangle drawing method, calls appropriate detection text 1484 | 1485 | Log("Done."); 1486 | } 1487 | } 1488 | } 1489 | 1490 | // add new entry in left list 1491 | public void CreateListItem(string filename, string date, string camera, string objects_and_confidence, string object_positions) 1492 | { 1493 | string success; 1494 | if (objects_and_confidence.Contains("%") && !objects_and_confidence.Contains(':')) 1495 | { 1496 | success = "true"; 1497 | } 1498 | else 1499 | { 1500 | success = "false"; 1501 | } 1502 | MethodInvoker LabelUpdate = delegate 1503 | { 1504 | if (checkListFilters(camera, success, objects_and_confidence)) //only show the entry in the history list if no filter applies 1505 | { 1506 | ListViewItem item; 1507 | if (success == "true") 1508 | { 1509 | item = new ListViewItem(new string[] { filename, date, camera, objects_and_confidence, object_positions, "✓" }); 1510 | } 1511 | else 1512 | { 1513 | item = new ListViewItem(new string[] { filename, date, camera, objects_and_confidence, object_positions, "X" }); 1514 | } 1515 | 1516 | list1.Items.Insert(0, item); 1517 | 1518 | ResizeListViews(); 1519 | } 1520 | 1521 | 1522 | 1523 | //update history CSV 1524 | string line = $"{filename}|{date}|{camera}|{objects_and_confidence}|{object_positions}|{success}"; 1525 | try 1526 | { 1527 | using (StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "cameras/history.csv", append: true)) 1528 | { 1529 | sw.WriteLine(line); 1530 | } 1531 | } 1532 | catch { } 1533 | }; 1534 | Invoke(LabelUpdate); 1535 | 1536 | 1537 | } 1538 | 1539 | //remove entry from left list 1540 | public void DeleteListItem(string filename) 1541 | { 1542 | Log($"Removing alert image {filename} from history list and from cameras/history.csv ..."); 1543 | MethodInvoker LabelUpdate = delegate 1544 | { 1545 | ListViewItem listviewitem = new ListViewItem(); 1546 | for (int i = 0; i < list1.Items.Count; i++) 1547 | { 1548 | listviewitem = list1.Items[i]; 1549 | if (filename == listviewitem.Text) 1550 | { 1551 | list1.Items.Remove(listviewitem); 1552 | break; 1553 | } 1554 | } 1555 | ResizeListViews(); 1556 | 1557 | //remove entry from history csv 1558 | try 1559 | { 1560 | var oldLines = System.IO.File.ReadAllLines(@"cameras/history.csv"); 1561 | var newLines = oldLines.Where(line => !line.Split('|')[0].Contains(filename)); 1562 | System.IO.File.WriteAllLines(@"cameras/history.csv", newLines); 1563 | } 1564 | catch 1565 | { 1566 | Log("ERROR: Can't write to cameras/history.csv!"); 1567 | } 1568 | 1569 | }; 1570 | 1571 | Invoke(LabelUpdate); 1572 | } 1573 | 1574 | //remove all obsolete entries (associated image does not exist anymore) from the history.csv 1575 | public void CleanCSVList() 1576 | { 1577 | Log($"Cleaning cameras/history.csv if neccessary..."); 1578 | MethodInvoker LabelUpdate = delegate 1579 | { 1580 | try 1581 | { 1582 | string[] oldLines = System.IO.File.ReadAllLines(@"cameras/history.csv"); //old history.csv 1583 | List newLines = new List(); //new history.csv 1584 | newLines.Add(oldLines[0]); // add title line from old to new history.csv 1585 | 1586 | foreach (string line in oldLines.Skip(1)) //check for every line except title line if associated image still exists in input folder 1587 | { 1588 | if (System.IO.File.Exists(input_path + "/" + line.Split('|')[0]) && input_path != "") 1589 | { 1590 | newLines.Add(line); 1591 | } 1592 | } 1593 | System.IO.File.WriteAllLines(@"cameras/history.csv", newLines); //write new history.csv 1594 | } 1595 | catch 1596 | { 1597 | Log("ERROR: Can't clean the cameras/history.csv!"); 1598 | } 1599 | 1600 | }; 1601 | Invoke(LabelUpdate); 1602 | } 1603 | 1604 | //load stored entries in history CSV into history ListView 1605 | private void LoadFromCSV() 1606 | { 1607 | try 1608 | { 1609 | Log("Loading history list from cameras/history.csv ..."); 1610 | 1611 | //delete obsolete entries from history.csv 1612 | //CleanCSVList(); //removed to load the history list faster 1613 | 1614 | List result = new List(); //List that later on will be containing all lines of the csv file 1615 | 1616 | //load all lines except the first line into List (the first line is the table heading and not an alert entry) 1617 | foreach (string line in System.IO.File.ReadAllLines(@"cameras/history.csv").Skip(1)) 1618 | { 1619 | result.Add(line); 1620 | } 1621 | 1622 | List itemsToDelete = new List(); //stores all filenames of history.csv entries that need to be removed 1623 | 1624 | MethodInvoker LabelUpdate = delegate 1625 | { 1626 | list1.Items.Clear(); 1627 | 1628 | //load all List elements into the ListView for each row 1629 | foreach (var val in result) 1630 | { 1631 | string camera = val.Split('|')[2]; 1632 | string success = val.Split('|')[5]; 1633 | string objects_and_confidence = val.Split('|')[3]; 1634 | if (!checkListFilters(camera, success, objects_and_confidence)) { continue; } //do not load the entry if a filter applies (checking as early as possible) 1635 | string filename = val.Split('|')[0]; 1636 | string date = val.Split('|')[1]; 1637 | string object_positions = val.Split('|')[4]; 1638 | 1639 | 1640 | 1641 | 1642 | 1643 | ListViewItem item; 1644 | if (success == "true") 1645 | { 1646 | item = new ListViewItem(new string[] { filename, date, camera, objects_and_confidence, object_positions, "✓" }); 1647 | } 1648 | else 1649 | { 1650 | item = new ListViewItem(new string[] { filename, date, camera, objects_and_confidence, object_positions, "X" }); 1651 | } 1652 | 1653 | list1.Items.Insert(0, item); 1654 | } 1655 | 1656 | ResizeListViews(); 1657 | 1658 | }; 1659 | Invoke(LabelUpdate); 1660 | } 1661 | catch { } 1662 | } 1663 | 1664 | //check if a filter applies on given string of history list entry 1665 | private bool checkListFilters(string cameraname, string success, string objects_and_confidence) 1666 | { 1667 | if (!objects_and_confidence.Contains("person") && cb_filter_person.Checked) { return false; } 1668 | if (!(objects_and_confidence.Contains("car") || 1669 | objects_and_confidence.Contains("boat") || 1670 | objects_and_confidence.Contains("bicycle") || 1671 | objects_and_confidence.Contains("truck") || 1672 | objects_and_confidence.Contains("airplane") || 1673 | objects_and_confidence.Contains("motorcycle") || 1674 | objects_and_confidence.Contains("horse")) && cb_filter_vehicle.Checked) { return false; } 1675 | if (!(objects_and_confidence.Contains("dog") || 1676 | objects_and_confidence.Contains("sheep") || 1677 | objects_and_confidence.Contains("bird") || 1678 | objects_and_confidence.Contains("cow") || 1679 | objects_and_confidence.Contains("cat") || 1680 | objects_and_confidence.Contains("horse") || 1681 | objects_and_confidence.Contains("bear")) && cb_filter_animal.Checked) { return false; } 1682 | if (success != "true" && cb_filter_success.Checked) { return false; } //if filter "only successful detections" is enabled, don't load false alerts 1683 | if (success == "true" && cb_filter_nosuccess.Checked) { return false; } //if filter "only unsuccessful detections" is enabled, don't load true alerts 1684 | if (comboBox_filter_camera.Text != "All Cameras" && cameraname != comboBox_filter_camera.Text.Substring(3)) { return false; } 1685 | return true; 1686 | } 1687 | 1688 | 1689 | 1690 | //EVENTS 1691 | 1692 | //EVENT: new image added to input_path -> START AI DETECTION 1693 | async void OnCreatedAsync(object source, FileSystemEventArgs e) 1694 | { 1695 | System.Threading.Thread.Sleep(file_access_delay); //shorty wait to ensure that the whole image is saved correctly 1696 | 1697 | while (detection_running == true) { } //wait until other detection process is finished 1698 | detection_running = true; //set marker variable to show that a new detection process is running 1699 | 1700 | //output "Processing Image" to Overview Tab 1701 | MethodInvoker LabelUpdate = delegate { label2.Text = $"Processing Image..."; }; 1702 | Invoke(LabelUpdate); 1703 | 1704 | 1705 | await DetectObjects(Path.Combine(input_path, e.Name)); //ai process image 1706 | 1707 | //output Running on Overview Tab 1708 | LabelUpdate = delegate { label2.Text = "Running"; }; 1709 | Invoke(LabelUpdate); 1710 | 1711 | //only update charts if stats tab is open 1712 | 1713 | LabelUpdate = delegate 1714 | { 1715 | Console.WriteLine(tabControl1.SelectedIndex); 1716 | 1717 | if (tabControl1.SelectedIndex == 1) 1718 | { 1719 | 1720 | UpdatePieChart(); UpdateTimeline(); UpdateConfidenceChart(); 1721 | Console.WriteLine("updated"); 1722 | } 1723 | }; 1724 | Invoke(LabelUpdate); 1725 | 1726 | 1727 | 1728 | detection_running = false; //reset variable 1729 | 1730 | } 1731 | 1732 | //event: image in input_path renamed 1733 | void OnRenamed(object source, RenamedEventArgs e) 1734 | { 1735 | DeleteListItem(e.OldName); 1736 | //CreateListItem(e.Name); 1737 | } 1738 | 1739 | //event: image in input path deleted 1740 | void OnDeleted(object source, FileSystemEventArgs e) 1741 | { 1742 | DeleteListItem(e.Name); 1743 | } 1744 | 1745 | //event: load selected image to picturebox 1746 | private void list1_SelectedIndexChanged(object sender, EventArgs e) //Bild ändern 1747 | { 1748 | try 1749 | { 1750 | if (list1.SelectedItems.Count > 0) 1751 | { 1752 | using (var img = new Bitmap(input_path + "/" + list1.SelectedItems[0].Text)) 1753 | { 1754 | pictureBox1.BackgroundImage = new Bitmap(img); //load actual image as background, so that an overlay can be added as the image 1755 | } 1756 | showHideMask(); 1757 | lbl_objects.Text = list1.SelectedItems[0].SubItems[3].Text; 1758 | } 1759 | } 1760 | catch (Exception ex) 1761 | { 1762 | Log($"ERROR: Loading entry from History list failed. This might have happened because obsolete entries weren't correctly deleted. {ex.GetType().ToString()} | {ex.Message.ToString()} (code: {ex.HResult} )"); 1763 | 1764 | //delete entry that caused the issue 1765 | try 1766 | { 1767 | DeleteListItem(list1.SelectedItems[0].Text); 1768 | } 1769 | //if deleting fails because the filename could not be retrieved, do a complete clean up 1770 | catch 1771 | { 1772 | CleanCSVList(); 1773 | LoadFromCSV(); 1774 | } 1775 | } 1776 | 1777 | 1778 | } 1779 | 1780 | //event: show mask button clicked 1781 | private void cb_showMask_CheckedChanged(object sender, EventArgs e) 1782 | { 1783 | if (list1.SelectedItems.Count > 0) 1784 | { 1785 | showHideMask(); 1786 | } 1787 | } 1788 | 1789 | //event: show objects button clicked 1790 | private void cb_showObjects_MouseUp(object sender, MouseEventArgs e) 1791 | { 1792 | if (list1.SelectedItems.Count > 0) 1793 | { 1794 | pictureBox1.Refresh(); 1795 | } 1796 | } 1797 | 1798 | //event: show history list filters button clicked 1799 | private void cb_showFilters_CheckedChanged(object sender, EventArgs e) 1800 | { 1801 | if (cb_showFilters.Checked) 1802 | { 1803 | cb_showFilters.Text = "˅ Filter"; 1804 | splitContainer1.Panel2Collapsed = false; 1805 | } 1806 | else 1807 | { 1808 | cb_showFilters.Text = "˄ Filter"; 1809 | splitContainer1.Panel2Collapsed = true; 1810 | } 1811 | 1812 | ResizeListViews(); 1813 | 1814 | } 1815 | 1816 | //event: filter "only revelant alerts" checked or unchecked 1817 | private void cb_filter_success_CheckedChanged(object sender, EventArgs e) 1818 | { 1819 | LoadFromCSV(); 1820 | } 1821 | 1822 | //event: filter "only alerts with people" checked or unchecked 1823 | private void cb_filter_person_CheckedChanged(object sender, EventArgs e) 1824 | { 1825 | LoadFromCSV(); 1826 | } 1827 | 1828 | //event: filter "only alerts with people" checked or unchecked 1829 | private void cb_filter_vehicle_CheckedChanged(object sender, EventArgs e) 1830 | { 1831 | LoadFromCSV(); 1832 | } 1833 | 1834 | //event: filter "only alerts with animals" checked or unchecked 1835 | private void cb_filter_animal_CheckedChanged(object sender, EventArgs e) 1836 | { 1837 | LoadFromCSV(); 1838 | } 1839 | 1840 | //event: filter "only false / irrevelant alerts" checked or unchecked 1841 | private void cb_filter_nosuccess_CheckedChanged(object sender, EventArgs e) 1842 | { 1843 | LoadFromCSV(); 1844 | } 1845 | 1846 | //event: filter camera dropdown changed 1847 | private void comboBox_filter_camera_SelectedIndexChanged(object sender, EventArgs e) 1848 | { 1849 | LoadFromCSV(); 1850 | } 1851 | 1852 | //---------------------------------------------------------------------------------------------------------- 1853 | //CAMERAS TAB 1854 | //---------------------------------------------------------------------------------------------------------- 1855 | 1856 | //BASIC METHODS 1857 | 1858 | // load cameras to camera list 1859 | public void LoadCameras() 1860 | { 1861 | list2.Items.Clear(); 1862 | 1863 | try 1864 | { 1865 | string[] files = Directory.GetFiles("./cameras", $"*.txt"); //load all settings files in a string array 1866 | 1867 | //create a camera object for every camera settings file 1868 | int i = 0; 1869 | foreach (string file in files) 1870 | { 1871 | string result = LoadCamera(file); //do LoadCamera() and save returned result in string 1872 | Log(result); 1873 | 1874 | //if LoadCamera() returned an error 1875 | if (result.Contains("ERROR")) 1876 | { 1877 | MessageBox.Show($"Could not load config file {file}: {result}"); 1878 | } 1879 | 1880 | //Add loaded camera to list2 1881 | ListViewItem item = new ListViewItem(new string[] { CameraList[i].name }); 1882 | item.Tag = file; 1883 | list2.Items.Add(item); 1884 | i++; 1885 | 1886 | } 1887 | } 1888 | catch 1889 | { 1890 | Log("ERROR LoadCameras() failed."); 1891 | MessageBox.Show("ERROR LoadCameras() failed."); 1892 | } 1893 | 1894 | //select first camera 1895 | if (list2.Items.Count > 0) 1896 | { 1897 | list2.Items[0].Selected = true; 1898 | } 1899 | } 1900 | 1901 | //load existing camera (settings file exists) into CameraList, into Stats dropdown and into History filter dropdown 1902 | private string LoadCamera(string config_path) 1903 | { 1904 | //check if camera with specified name or its prefix already exists. If yes, then abort. 1905 | foreach (Camera c in CameraList) 1906 | { 1907 | if (c.name == Path.GetFileNameWithoutExtension(config_path)) 1908 | { 1909 | return ($"ERROR: Camera name must be unique,{Path.GetFileNameWithoutExtension(config_path)} already exists."); 1910 | } 1911 | if (c.prefix == System.IO.File.ReadAllLines(config_path)[2].Split('"')[1]) 1912 | { 1913 | return ($"ERROR: Every camera must have a unique prefix ('Input file begins with'), but the prefix of {Path.GetFileNameWithoutExtension(config_path)} equals the prefix of the existing camera {c.name} ."); 1914 | } 1915 | } 1916 | Camera cam = new Camera(); //create new camera object 1917 | Log("read config"); 1918 | cam.ReadConfig(config_path); //read camera's config from file 1919 | Log("add"); 1920 | CameraList.Add(cam); //add created camera object to CameraList 1921 | 1922 | //add camera to combobox on overview tab and to camera filter combobox in the History tab 1923 | comboBox1.Items.Add($" {cam.name}"); 1924 | comboBox_filter_camera.Items.Add($" {cam.name}"); 1925 | 1926 | return ($"SUCCESS: {Path.GetFileNameWithoutExtension(config_path)} loaded."); 1927 | } 1928 | 1929 | //add camera 1930 | private string AddCamera(string name, string prefix, string trigger_urls_as_string, string triggering_objects_as_string, bool telegram_enabled, bool enabled, double cooldown_time, int threshold_lower, int threshold_upper) 1931 | { 1932 | //check if camera with specified name already exists. If yes, then abort. 1933 | foreach (Camera c in CameraList) 1934 | { 1935 | if (c.name == name) 1936 | { 1937 | MessageBox.Show($"ERROR: Camera name must be unique,{name} already exists."); 1938 | return ($"ERROR: Camera name must be unique,{name} already exists."); 1939 | } 1940 | } 1941 | 1942 | //check if name is empty 1943 | if (name == "") 1944 | { 1945 | MessageBox.Show($"ERROR: Camera name may not be empty."); 1946 | return ($"ERROR: Camera name may not be empty."); 1947 | } 1948 | 1949 | Camera cam = new Camera(); //create new camera object 1950 | cam.WriteConfig(name, prefix, triggering_objects_as_string, trigger_urls_as_string, telegram_enabled, enabled, cooldown_time, threshold_lower, threshold_upper); //set parameters 1951 | CameraList.Add(cam); //add created camera object to CameraList 1952 | 1953 | //add camera to list2 1954 | ListViewItem item = new ListViewItem(new string[] { name }); 1955 | item.Tag = name; 1956 | list2.Items.Add(item); 1957 | 1958 | //add camera to combobox on overview tab and to camera filter combobox in the History tab 1959 | comboBox1.Items.Add($" {cam.name}"); 1960 | comboBox_filter_camera.Items.Add($" {cam.name}"); 1961 | 1962 | //select first camera 1963 | if (list2.Items.Count == 1) 1964 | { 1965 | list2.Items[0].Selected = true; 1966 | } 1967 | 1968 | return ($"SUCCESS: {name} created."); 1969 | } 1970 | 1971 | //change settings of camera 1972 | private string UpdateCamera(string oldname, string name, string prefix, string trigger_urls_as_string, string triggering_objects_as_string, bool telegram_enabled, bool enabled, double cooldown_time, int threshold_lower, int threshold_upper) 1973 | { 1974 | //1. CHECK NEW VALUES 1975 | //check if name is empty 1976 | if (name == "") 1977 | { 1978 | DisplayCameraSettings(); //reset displayed settings 1979 | return ($"WARNING: Camera name may not be empty."); 1980 | } 1981 | 1982 | //check if camera with specified name exists. If no, then abort. 1983 | if (!CameraList.Exists(x => x.name == oldname)) 1984 | { 1985 | return ($"WARNING: Camera can't be modified because old name {oldname} wasn't found."); 1986 | } 1987 | 1988 | // check if the new name isn't taken by another camera already (in case the name was changed) 1989 | if (name != oldname && CameraList.Exists(x => String.Equals(name, x.name, StringComparison.OrdinalIgnoreCase))) 1990 | { 1991 | DisplayCameraSettings(); //reset displayed settings 1992 | return ($"WARNING: Camera name must be unique, but new camera name {name} already exists."); 1993 | } 1994 | 1995 | int index = -1; 1996 | index = CameraList.FindIndex(x => x.name == oldname); //index of specified camera in list 1997 | 1998 | if (index == -1) { Log("ERROR updating camera, could not find original camera profile."); } 1999 | 2000 | //check if new prefix isn't already taken by another camera 2001 | if (prefix != CameraList[index].prefix && CameraList.Exists(x => x.prefix == prefix)) 2002 | { 2003 | DisplayCameraSettings(); //reset displayed settings 2004 | return ($"WARNING: Every camera must have a unique prefix ('Input file begins with'), but the prefix of {name} already exists."); 2005 | } 2006 | 2007 | //2. WRITE CONFIG 2008 | CameraList[index].WriteConfig(name, prefix, triggering_objects_as_string, trigger_urls_as_string, telegram_enabled, enabled, cooldown_time, threshold_lower, threshold_upper); //set parameters 2009 | 2010 | //3. UPDATE LIST2 2011 | //update list2 entry 2012 | var item = list2.FindItemWithText(oldname); 2013 | list2.Items[list2.Items.IndexOf(item)].Text = name; 2014 | 2015 | 2016 | //update camera combobox on overview tab and to camera filter combobox in the History tab 2017 | comboBox1.Items[comboBox1.Items.IndexOf($" {oldname}")] = $" {name}"; 2018 | comboBox_filter_camera.Items[comboBox_filter_camera.Items.IndexOf($" {oldname}")] = $" {name}"; 2019 | 2020 | 2021 | return ($"SUCCESS: Camera {oldname} was updated to {name}."); 2022 | } 2023 | 2024 | //remove camera 2025 | private void RemoveCamera(string name) 2026 | { 2027 | Log($"Removing camera {name}..."); 2028 | if (list2.Items.Count > 0) //if list is empty, nothing can be deleted 2029 | { 2030 | if (CameraList.Exists(x => x.name == name)) //check if camera with specified name exists in list 2031 | { 2032 | 2033 | //find index of specified camera in list 2034 | int index = -1; 2035 | 2036 | //check for each camera in the cameralist if its name equals the name of the camera that is selected to be deleted 2037 | for (int i = 0; i < CameraList.Count; i++) 2038 | { 2039 | if (CameraList[i].name.Equals(name)) 2040 | { 2041 | index = i; 2042 | 2043 | } 2044 | } 2045 | 2046 | if (index != -1) //only delete camera if index is known (!= its default value -1) 2047 | { 2048 | CameraList[index].Delete(); //delete settings file of specified camera 2049 | 2050 | //move all cameras following the specified camera one position forward in the list 2051 | //the position of the specified camera is overridden with the following camera, the position of the following camera is overridden with its follower, and so on 2052 | for (int i = index; i < CameraList.Count - 1; i++) 2053 | { 2054 | CameraList[i] = CameraList[i + 1]; 2055 | } 2056 | 2057 | CameraList.Remove(CameraList[CameraList.Count - 1]); //lastly, remove camera from list 2058 | 2059 | //remove list2 entry 2060 | var item = list2.FindItemWithText(name); 2061 | list2.Items[list2.Items.IndexOf(item)].Remove(); 2062 | 2063 | //remove camera from combobox on overview tab and from camera filter combobox in the History tab 2064 | comboBox1.Items.Remove($" {name}"); 2065 | comboBox_filter_camera.Items.Remove($" {name}"); 2066 | 2067 | //select first camera 2068 | if (list2.Items.Count > 0) 2069 | { 2070 | list2.Items[0].Selected = true; 2071 | } 2072 | 2073 | //if list2 is empty, clear settings fields (to prevent that values of a deleted camera are shown) 2074 | if (list2.Items.Count == 0) 2075 | { 2076 | tbName.Text = ""; 2077 | tbPrefix.Text = ""; 2078 | cb_enabled.Checked = false; 2079 | CheckBox[] cbarray = new CheckBox[] { cb_airplane, cb_bear, cb_bicycle, cb_bird, cb_boat, cb_bus, cb_car, cb_cat, cb_cow, cb_dog, cb_horse, cb_motorcycle, cb_person, cb_sheep, cb_truck }; 2080 | foreach (CheckBox c in cbarray) 2081 | { 2082 | c.Checked = false; 2083 | } 2084 | tbTriggerUrl.Text = ""; 2085 | cb_telegram.Checked = false; 2086 | } 2087 | } 2088 | else 2089 | { 2090 | Log("ERROR: Can't find the selected camera, camera wasn't deleted."); 2091 | } 2092 | 2093 | 2094 | } 2095 | } 2096 | } 2097 | 2098 | //display camera settings for selected camera 2099 | private void DisplayCameraSettings() 2100 | { 2101 | if (list2.SelectedItems.Count > 0) 2102 | { 2103 | 2104 | tbName.Text = list2.SelectedItems[0].Text; //load name textbox from name in list2 2105 | 2106 | //load remaining settings from Camera.cs object 2107 | 2108 | //all camera objects are stored in the list CameraList, so firstly the position (stored in the second column for each entry) is gathered 2109 | int i = CameraList.FindIndex(x => x.name == list2.SelectedItems[0].Text); 2110 | 2111 | //load cameras stats 2112 | 2113 | string stats = $"Alerts: {CameraList[i].stats_alerts.ToString()} | Irrelevant Alerts: {CameraList[i].stats_irrelevant_alerts.ToString()} | False Alerts: {CameraList[i].stats_false_alerts.ToString()}"; 2114 | lbl_camstats.Text = stats; 2115 | 2116 | //load if ai detection is active for the camera 2117 | if (CameraList[i].enabled == true) 2118 | { 2119 | cb_enabled.Checked = true; 2120 | } 2121 | else 2122 | { 2123 | cb_enabled.Checked = false; 2124 | } 2125 | tbPrefix.Text = CameraList[i].prefix; //load 'input file begins with' 2126 | lbl_prefix.Text = tbPrefix.Text + ".××××××.jpg"; //prefix live preview 2127 | tbTriggerUrl.Text = CameraList[i].trigger_urls_as_string; //load trigger url 2128 | tb_cooldown.Text = CameraList[i].cooldown_time.ToString(); //load cooldown time 2129 | tb_threshold_lower.Text = CameraList[i].threshold_lower.ToString(); //load lower threshold value 2130 | tb_threshold_upper.Text = CameraList[i].threshold_upper.ToString(); // load upper threshold value 2131 | 2132 | //load telegram image sending on/off option 2133 | if (CameraList[i].telegram_enabled) 2134 | { 2135 | cb_telegram.Checked = true; 2136 | } 2137 | else 2138 | { 2139 | cb_telegram.Checked = false; 2140 | } 2141 | 2142 | 2143 | //load triggering objects 2144 | //first create arrays with all checkboxes stored in 2145 | CheckBox[] cbarray = new CheckBox[] { cb_airplane, cb_bear, cb_bicycle, cb_bird, cb_boat, cb_bus, cb_car, cb_cat, cb_cow, cb_dog, cb_horse, cb_motorcycle, cb_person, cb_sheep, cb_truck }; 2146 | //create array with strings of the triggering_objects related to the checkboxes in the same order 2147 | string[] cbstringarray = new string[] { "airplane", "bear", "bicycle", "bird", "boat", "bus", "car", "cat", "cow", "dog", "horse", "motorcycle", "person", "sheep", "truck" }; 2148 | 2149 | //clear all checkmarks 2150 | foreach (CheckBox cb in cbarray) 2151 | { 2152 | cb.Checked = false; 2153 | } 2154 | 2155 | //check for every triggering_object string if it is active in the settings file. If yes, check according checkbox 2156 | for (int j = 0; j < cbarray.Length; j++) 2157 | { 2158 | if (CameraList[i].triggering_objects_as_string.Contains(cbstringarray[j])) 2159 | { 2160 | cbarray[j].Checked = true; 2161 | } 2162 | } 2163 | } 2164 | } 2165 | 2166 | 2167 | 2168 | // SPECIAL METHODS 2169 | 2170 | //input file begins with live preview 2171 | private void tbPrefix_TextChanged(object sender, EventArgs e) 2172 | { 2173 | lbl_prefix.Text = tbPrefix.Text + ".××××××.jpg"; 2174 | } 2175 | 2176 | //event: if SPACE is pressed in trigger url field, automatically add a comma 2177 | private void tbTriggerUrl_KeyDown(object sender, KeyEventArgs e) 2178 | { 2179 | if (e.KeyCode == Keys.Space) 2180 | { 2181 | tbTriggerUrl.Text += ","; //add comma 2182 | tbTriggerUrl.Select(tbTriggerUrl.Text.Length, 0); //move cursor to end 2183 | } 2184 | } 2185 | 2186 | //event: if COMMA is pressed in trigger url field, automatically add a space behind it 2187 | private void tbTriggerUrl_KeyUp(object sender, KeyEventArgs e) 2188 | { 2189 | if (e.KeyCode == Keys.Oemcomma) 2190 | { 2191 | tbTriggerUrl.Text += " "; //add space 2192 | tbTriggerUrl.Select(tbTriggerUrl.Text.Length, 0); //move cursor to end 2193 | } 2194 | } 2195 | 2196 | //event: camera list another item selected 2197 | private void list2_SelectedIndexChanged(object sender, EventArgs e) 2198 | { 2199 | DisplayCameraSettings(); //display new item's settings 2200 | } 2201 | 2202 | //event: camera add button 2203 | private void btnCameraAdd_Click(object sender, EventArgs e) 2204 | { 2205 | 2206 | using (var form = new InputForm("Camera Name:", "New Camera", true)) 2207 | { 2208 | var result = form.ShowDialog(); 2209 | if (result == DialogResult.OK) 2210 | { 2211 | string name = form.text; 2212 | AddCamera(name, name, "", "person", false, true, 0, 0, 100); 2213 | } 2214 | } 2215 | } 2216 | 2217 | //event: save camera settings button 2218 | private void btnCameraSave_Click_1(object sender, EventArgs e) 2219 | { 2220 | if (list2.Items.Count > 0) 2221 | { 2222 | //1. GET SETTINGS INPUTTED 2223 | //all checkboxes in one array 2224 | CheckBox[] cbarray = new CheckBox[] { cb_airplane, cb_bear, cb_bicycle, cb_bird, cb_boat, cb_bus, cb_car, cb_cat, cb_cow, cb_dog, cb_horse, cb_motorcycle, cb_person, cb_sheep, cb_truck }; 2225 | //create array with strings of the triggering_objects related to the checkboxes in the same order 2226 | string[] cbstringarray = new string[] { "airplane", "bear", "bicycle", "bird", "boat", "bus", "car", "cat", "cow", "dog", "horse", "motorcycle", "person", "sheep", "truck" }; 2227 | 2228 | //go through all checkboxes and write all triggering_objects in one string 2229 | string triggering_objects_as_string = ""; 2230 | for (int i = 0; i < cbarray.Length; i++) 2231 | { 2232 | if (cbarray[i].Checked == true) 2233 | { 2234 | triggering_objects_as_string += $"{cbstringarray[i]}, "; 2235 | } 2236 | } 2237 | 2238 | //get cooldown time from textbox 2239 | Double.TryParse(tb_cooldown.Text, out double cooldown_time); 2240 | 2241 | //get lower and upper threshold values from textboxes 2242 | Int32.TryParse(tb_threshold_lower.Text, out int threshold_lower); 2243 | Int32.TryParse(tb_threshold_upper.Text, out int threshold_upper); 2244 | 2245 | 2246 | //2. UPDATE SETTINGS 2247 | // save new camera settings, display result in MessageBox 2248 | string result = UpdateCamera(list2.SelectedItems[0].Text, tbName.Text, tbPrefix.Text, tbTriggerUrl.Text, triggering_objects_as_string, cb_telegram.Checked, cb_enabled.Checked, cooldown_time, threshold_lower, threshold_upper); 2249 | 2250 | } 2251 | DisplayCameraSettings(); 2252 | } 2253 | 2254 | //event: delete camera button 2255 | private void btnCameraDel_Click(object sender, EventArgs e) 2256 | { 2257 | if (list2.Items.Count > 0) 2258 | { 2259 | using (var form = new InputForm($"Delete camera {list2.SelectedItems[0].Text} ?", "Delete Camera?", false)) 2260 | { 2261 | var result = form.ShowDialog(); 2262 | if (result == DialogResult.OK) 2263 | { 2264 | Log("about to del cam"); 2265 | RemoveCamera(list2.SelectedItems[0].Text); 2266 | } 2267 | } 2268 | } 2269 | } 2270 | 2271 | //event: DELETE key pressed 2272 | private void list2_KeyDown(object sender, KeyEventArgs e) 2273 | { 2274 | if (e.KeyCode == Keys.Delete) 2275 | { 2276 | if (list2.Items.Count > 0) 2277 | { 2278 | using (var form = new InputForm($"Delete camera {list2.SelectedItems[0].Text} ?", "Delete Camera?", false)) 2279 | { 2280 | var result = form.ShowDialog(); 2281 | if (result == DialogResult.OK) 2282 | { 2283 | RemoveCamera(list2.SelectedItems[0].Text); 2284 | } 2285 | } 2286 | } 2287 | } 2288 | } 2289 | 2290 | //event: leaving empty lower confidence limit textbox 2291 | private void tb_threshold_lower_Leave(object sender, EventArgs e) 2292 | { 2293 | if (tb_threshold_lower.Text == "") 2294 | { 2295 | tb_threshold_lower.Text = "0"; 2296 | } 2297 | } 2298 | 2299 | //event: leaving empty upper confidence limit textbox 2300 | private void tb_threshold_upper_Leave(object sender, EventArgs e) 2301 | { 2302 | if (tb_threshold_upper.Text == "") 2303 | { 2304 | tb_threshold_upper.Text = "100"; 2305 | } 2306 | } 2307 | 2308 | 2309 | 2310 | //---------------------------------------------------------------------------------------------------------- 2311 | //SETTING TAB 2312 | //---------------------------------------------------------------------------------------------------------- 2313 | 2314 | 2315 | //settings save button 2316 | private void BtnSettingsSave_Click_1(object sender, EventArgs e) 2317 | { 2318 | //save inputted settings into App.settings 2319 | Properties.Settings.Default.input_path = tbInput.Text; 2320 | Properties.Settings.Default.deepstack_url = tbDeepstackUrl.Text; 2321 | Properties.Settings.Default.telegram_chatid = tb_telegram_chatid.Text; 2322 | Properties.Settings.Default.telegram_token = tb_telegram_token.Text; 2323 | Properties.Settings.Default.log_everything = cb_log.Checked; 2324 | Properties.Settings.Default.send_errors = cb_send_errors.Checked; 2325 | Properties.Settings.Default.Save(); 2326 | 2327 | //update variables 2328 | input_path = Properties.Settings.Default.input_path; 2329 | deepstack_url = Properties.Settings.Default.deepstack_url; 2330 | telegram_chatid = Properties.Settings.Default.telegram_chatid; 2331 | telegram_chatids = telegram_chatid.Replace(" ", "").Split(','); //for multiple Telegram chats that receive alert images 2332 | telegram_token = Properties.Settings.Default.telegram_token; 2333 | log_everything = Properties.Settings.Default.log_everything; 2334 | send_errors = Properties.Settings.Default.send_errors; 2335 | 2336 | //update fswatcher to watch new input folder 2337 | UpdateFSWatcher(); 2338 | 2339 | //clean history.csv database 2340 | CleanCSVList(); 2341 | 2342 | //LoadList(); 2343 | } 2344 | 2345 | //input path select dialog button 2346 | private void btn_input_path_Click(object sender, EventArgs e) 2347 | { 2348 | using (CommonOpenFileDialog dialog = new CommonOpenFileDialog()) 2349 | { 2350 | dialog.InitialDirectory = "C:\\"; 2351 | dialog.IsFolderPicker = true; 2352 | if (dialog.ShowDialog() == CommonFileDialogResult.Ok) 2353 | { 2354 | tbInput.Text = dialog.FileName; 2355 | } 2356 | } 2357 | } 2358 | 2359 | //open log button 2360 | private void btn_open_log_Click(object sender, EventArgs e) 2361 | { 2362 | if (System.IO.File.Exists("log.txt")) 2363 | { 2364 | System.Diagnostics.Process.Start("log.txt"); 2365 | lbl_errors.Text = ""; 2366 | } 2367 | else 2368 | { 2369 | MessageBox.Show("log missing"); 2370 | } 2371 | 2372 | } 2373 | 2374 | //ask before closing AI Tool to prevent accidently closing 2375 | private void Shell_FormClosing(object sender, FormClosingEventArgs e) 2376 | { 2377 | if (Properties.Settings.Default.close_instantly <= 0) //if it's eigther enabled or not set -1 = not set | 0 = ask for confirmation | 1 = don't ask 2378 | { 2379 | using (var form = new InputForm($"Stop and close AI Tool?", "AI Tool", false)) 2380 | { 2381 | var result = form.ShowDialog(); 2382 | if (Properties.Settings.Default.close_instantly == -1) 2383 | { 2384 | //if it's the first time, ask if the confirmation dialog should ever appear again 2385 | using (var form1 = new InputForm($"Confirm closing AI Tool every time?", "AI Tool", false, "NO, Never!", "YES")) 2386 | { 2387 | var result1 = form1.ShowDialog(); 2388 | if (result1 == DialogResult.Cancel) 2389 | { 2390 | Properties.Settings.Default.close_instantly = 0; 2391 | Properties.Settings.Default.Save(); 2392 | } 2393 | else 2394 | { 2395 | Properties.Settings.Default.close_instantly = 1; 2396 | Properties.Settings.Default.Save(); 2397 | } 2398 | } 2399 | } 2400 | 2401 | e.Cancel = (result == DialogResult.Cancel); 2402 | } 2403 | } 2404 | 2405 | } 2406 | } 2407 | 2408 | 2409 | //classes for AI analysis 2410 | 2411 | class Response 2412 | { 2413 | 2414 | public bool success { get; set; } 2415 | public Object[] predictions { get; set; } 2416 | 2417 | } 2418 | 2419 | class Object 2420 | { 2421 | 2422 | public string label { get; set; } 2423 | public float confidence { get; set; } 2424 | public int y_min { get; set; } 2425 | public int x_min { get; set; } 2426 | public int y_max { get; set; } 2427 | public int x_max { get; set; } 2428 | 2429 | } 2430 | 2431 | 2432 | //enhanced TableLayoutPanel loads faster 2433 | public partial class DBLayoutPanel : TableLayoutPanel 2434 | { 2435 | public DBLayoutPanel() 2436 | { 2437 | SetStyle(ControlStyles.AllPaintingInWmPaint | 2438 | ControlStyles.OptimizedDoubleBuffer | 2439 | ControlStyles.UserPaint, true); 2440 | } 2441 | 2442 | public DBLayoutPanel(IContainer container) 2443 | { 2444 | container.Add(this); 2445 | SetStyle(ControlStyles.AllPaintingInWmPaint | 2446 | ControlStyles.OptimizedDoubleBuffer | 2447 | ControlStyles.UserPaint, true); 2448 | } 2449 | } 2450 | } 2451 | 2452 | 2453 | -------------------------------------------------------------------------------- /src/UI/UI.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {B8ACBD49-0830-4E34-B5B6-C876BEAE6F65} 8 | WinExe 9 | WindowsFormsApp2 10 | aitool 11 | v4.6.1 12 | 512 13 | true 14 | true 15 | false 16 | publish\ 17 | true 18 | Disk 19 | false 20 | Foreground 21 | 7 22 | Days 23 | false 24 | false 25 | true 26 | 2 27 | 1.67.0.%2a 28 | false 29 | true 30 | true 31 | 32 | 33 | AnyCPU 34 | true 35 | full 36 | false 37 | bin\Debug\ 38 | DEBUG;TRACE 39 | prompt 40 | 4 41 | 42 | 43 | AnyCPU 44 | pdbonly 45 | true 46 | bin\Release\ 47 | TRACE 48 | prompt 49 | 4 50 | 51 | 52 | logo.ico 53 | 54 | 55 | CF35D53B9A3FA151692C997D0106616CB25D8869 56 | 57 | 58 | UI_TemporaryKey.pfx 59 | 60 | 61 | true 62 | 63 | 64 | false 65 | 66 | 67 | 68 | ..\packages\Microsoft.WindowsAPICodePack.Core.1.1.0\lib\Microsoft.WindowsAPICodePack.dll 69 | 70 | 71 | ..\packages\Microsoft.WindowsAPICodePack.Shell.1.1.0\lib\Microsoft.WindowsAPICodePack.Shell.dll 72 | 73 | 74 | ..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll 75 | 76 | 77 | ..\packages\SixLabors.Core.1.0.0-beta0007\lib\netstandard2.0\SixLabors.Core.dll 78 | 79 | 80 | ..\packages\SixLabors.ImageSharp.1.0.0-beta0006\lib\netstandard2.0\SixLabors.ImageSharp.dll 81 | 82 | 83 | 84 | ..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll 85 | 86 | 87 | 88 | 89 | ..\packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll 90 | 91 | 92 | 93 | ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll 94 | 95 | 96 | ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.1\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | ..\packages\Telegram.Bot.14.11.0\lib\net45\Telegram.Bot.dll 110 | 111 | 112 | 113 | 114 | 115 | Form 116 | 117 | 118 | Shell.cs 119 | 120 | 121 | Form 122 | 123 | 124 | InputForm.cs 125 | 126 | 127 | 128 | 129 | Shell.cs 130 | 131 | 132 | InputForm.cs 133 | 134 | 135 | ResXFileCodeGenerator 136 | Designer 137 | Resources.Designer.cs 138 | 139 | 140 | 141 | SettingsSingleFileGenerator 142 | Settings.Designer.cs 143 | 144 | 145 | True 146 | True 147 | Resources.resx 148 | 149 | 150 | True 151 | Settings.settings 152 | True 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | False 183 | Microsoft .NET Framework 4.6.1 %28x86 and x64%29 184 | true 185 | 186 | 187 | False 188 | .NET Framework 3.5 SP1 189 | false 190 | 191 | 192 | 193 | -------------------------------------------------------------------------------- /src/UI/logo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gentlepumpkin/bi-aidetection/961464451633d30e72d05350f488a59f8828d705/src/UI/logo.ico -------------------------------------------------------------------------------- /src/UI/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/bi-aidetection.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.489 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UI", "UI\UI.csproj", "{B8ACBD49-0830-4E34-B5B6-C876BEAE6F65}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {B8ACBD49-0830-4E34-B5B6-C876BEAE6F65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {B8ACBD49-0830-4E34-B5B6-C876BEAE6F65}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {B8ACBD49-0830-4E34-B5B6-C876BEAE6F65}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {B8ACBD49-0830-4E34-B5B6-C876BEAE6F65}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {70C9FD94-C962-456A-9C9F-796B13AD6FA0} 24 | EndGlobalSection 25 | EndGlobal 26 | --------------------------------------------------------------------------------