├── .gitattributes ├── .gitignore ├── README.md ├── TessOCR.7z ├── arcsong.db ├── catch_stat.py ├── ingame.png ├── inmenu.png ├── pytesseract ├── __init__.py └── pytesseract.py ├── rpc.py ├── run.bat ├── sc_0c9b5.png ├── temp └── empty ├── testjpn.png └── update_stat.py /.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 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arcaea_Discord_Rich_Presence 2 | 3 | - 将Arcaea游戏状态实时显示到Discord中 4 | 5 | 6 | 7 | # 部署 8 | 9 | - 注意:仅支持安卓设备 10 | - 需要自行安装`adb` 11 | - 需要`Python3`环境 12 | 13 | ```shell 14 | pip install pypresence 15 | pip install Pillow 16 | ``` 17 | 18 | - 将`TessOCR.7z`解压到项目根目录 19 | 20 | 21 | 22 | # How to use 23 | 24 | - 手机连接电脑,打开USB调试 25 | - 打开Arcaea 26 | 27 | - 双击`run.bat`运行 28 | 29 | 30 | 31 | # 效果演示 32 | 33 | ![image](https://github.com/chinosk114514/Arcaea_Discord_Rich_Presence/blob/master/inmenu.png) 34 | 35 | ![image](https://github.com/chinosk114514/Arcaea_Discord_Rich_Presence/blob/master/ingame.png) -------------------------------------------------------------------------------- /TessOCR.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/TessOCR.7z -------------------------------------------------------------------------------- /arcsong.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/arcsong.db -------------------------------------------------------------------------------- /catch_stat.py: -------------------------------------------------------------------------------- 1 | import PIL 2 | from PIL import ImageEnhance 3 | import pytesseract 4 | import json 5 | import sqlite3 6 | import difflib 7 | import re 8 | 9 | ignore_list = ["cubesato","tama","Apollo program"] 10 | 11 | def query_db(db_path, sql, para=""): 12 | connection = sqlite3.connect(db_path) 13 | cursor = connection.cursor() 14 | cursor.execute(sql, para) 15 | nb = cursor.fetchall() 16 | #connection.commit() 17 | cursor.close() 18 | connection.close() 19 | return(nb) 20 | 21 | def get_text_right(s, f): 22 | ''' 23 | 原文本,查找文本 24 | ''' 25 | l = s.rfind(f) 26 | return(s[l + len(f):]) 27 | 28 | def get_str_simi(str1, str2): 29 | return(difflib.SequenceMatcher(None, str1, str2).quick_ratio()) 30 | 31 | def get_diff(input): 32 | getlist = re.findall("\d+\+?", input) 33 | return(''.join(getlist)) 34 | 35 | def get_num_from_str(input): 36 | getlist = re.findall("\d+", input) 37 | return(''.join(getlist)) 38 | 39 | def ocr(filename, lang): #2日语 40 | im = PIL.Image.open(filename) 41 | iw = im.width 42 | ih = im.height 43 | im = im.crop((int(iw*0.75), 0, iw, int(ih*0.33))) 44 | im = ImageEnhance.Brightness(im).enhance(0.85) 45 | # 转化为8bit的黑白图片 46 | im = im.convert('L') 47 | # 二值化,采用阈值分割算法,threshold为分割点 48 | threshold = 140 49 | table = [] 50 | for j in range(256): 51 | if j < threshold: 52 | table.append(0) 53 | else: 54 | table.append(1) 55 | im = im.point(table, '1') 56 | 57 | if(lang == '2'): 58 | result = pytesseract.image_to_string(im, lang="eng+jpn+chi_sim", config='') 59 | else: 60 | result = pytesseract.image_to_string(im, lang="eng", config='') 61 | result = result.split('\n') 62 | #print(result) 63 | return(result) 64 | 65 | 66 | def get_info(tlist:list): 67 | songs = query_db("arcsong.db", "select `name_en`,`name_jp` from songs") 68 | #tlist = ['SCORE ~ ad', 'a', ': See een Beyond 11', '‘2 ses', 'aw Tempestissimo', 'NM Bf »', ', Whe if t+pazolite', '\x0c'] 69 | difflist = ["Past", "Present", "Future", "Beyond"] 70 | diffstr = '' 71 | diff_flag = False #跳循环 72 | for d in difflist: 73 | diff_index = -1 #记录难度位置 74 | for g in tlist: 75 | diff_index += 1 76 | if(d in g): 77 | diff_flag = True 78 | diffstr = d 79 | diffnum = get_diff(get_text_right(g, d)) 80 | try: 81 | diffint = int(get_num_from_str(diffnum)) 82 | if(diffint <= 0 or diffint >= 12): 83 | diffnum = '' 84 | except: 85 | pass 86 | break 87 | if(diff_flag == True): 88 | break 89 | 90 | if(diffstr == ''): #未找到难度信息 91 | return("In Menu", "0") 92 | 93 | score = "0" 94 | for sc in tlist[:diff_index]: 95 | _sc = re.findall("[0-9]([0-9]{7})", sc) 96 | if(len(_sc) == 1): 97 | score = _sc[0] 98 | #print(score) 99 | break 100 | 101 | maxsimi = 0 102 | maxsimi_song = '' 103 | for sn in songs: 104 | for song in sn: #song-单曲名 105 | #print(song) 106 | if(song == ''): 107 | #print(114) 108 | continue 109 | for wd in tlist[diff_index + 1:]: 110 | pig = False 111 | for ig in ignore_list: 112 | if(wd in ig): 113 | pig = True 114 | break 115 | if(pig == True): 116 | continue 117 | s_now = get_str_simi(song, wd.replace(" ",'').replace("〇", "の")) 118 | if(s_now > maxsimi): 119 | maxsimi = s_now 120 | maxsimi_song = song 121 | 122 | #print(maxsimi_song, maxsimi) 123 | return(maxsimi_song + ' ' + diffstr + ' ' + diffnum, score) 124 | 125 | 126 | def stat_identify(filename, lang): 127 | tlist = ocr(filename, lang) 128 | ret = get_info(tlist) 129 | return(ret) 130 | 131 | #print(get_info()) -------------------------------------------------------------------------------- /ingame.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/ingame.png -------------------------------------------------------------------------------- /inmenu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/inmenu.png -------------------------------------------------------------------------------- /pytesseract/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa: F401 2 | from .pytesseract import ALTONotSupported 3 | from .pytesseract import get_languages 4 | from .pytesseract import get_tesseract_version 5 | from .pytesseract import image_to_alto_xml 6 | from .pytesseract import image_to_boxes 7 | from .pytesseract import image_to_data 8 | from .pytesseract import image_to_osd 9 | from .pytesseract import image_to_pdf_or_hocr 10 | from .pytesseract import image_to_string 11 | from .pytesseract import Output 12 | from .pytesseract import run_and_get_output 13 | from .pytesseract import TesseractError 14 | from .pytesseract import TesseractNotFoundError 15 | from .pytesseract import TSVNotSupported 16 | 17 | 18 | __version__ = '0.3.8' 19 | -------------------------------------------------------------------------------- /pytesseract/pytesseract.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import re 3 | import shlex 4 | import string 5 | import subprocess 6 | import sys 7 | from contextlib import contextmanager 8 | from csv import QUOTE_NONE 9 | from distutils.version import LooseVersion 10 | from errno import ENOENT 11 | from functools import wraps 12 | from glob import iglob 13 | from io import BytesIO 14 | from os import environ 15 | from os import extsep 16 | from os import linesep 17 | from os import remove 18 | from os.path import normcase 19 | from os.path import normpath 20 | from os.path import realpath 21 | from pkgutil import find_loader 22 | from tempfile import NamedTemporaryFile 23 | from time import sleep 24 | 25 | try: 26 | from PIL import Image 27 | except ImportError: 28 | import Image 29 | 30 | 31 | tesseract_cmd = sys.path[0] + '\\TessOCR\\tesseract.exe' 32 | 33 | numpy_installed = find_loader('numpy') is not None 34 | if numpy_installed: 35 | from numpy import ndarray 36 | 37 | pandas_installed = find_loader('pandas') is not None 38 | if pandas_installed: 39 | import pandas as pd 40 | 41 | DEFAULT_ENCODING = 'utf-8' 42 | LANG_PATTERN = re.compile('^[a-z_]+$') 43 | RGB_MODE = 'RGB' 44 | SUPPORTED_FORMATS = { 45 | 'JPEG', 46 | 'PNG', 47 | 'PBM', 48 | 'PGM', 49 | 'PPM', 50 | 'TIFF', 51 | 'BMP', 52 | 'GIF', 53 | 'WEBP', 54 | } 55 | 56 | OSD_KEYS = { 57 | 'Page number': ('page_num', int), 58 | 'Orientation in degrees': ('orientation', int), 59 | 'Rotate': ('rotate', int), 60 | 'Orientation confidence': ('orientation_conf', float), 61 | 'Script': ('script', str), 62 | 'Script confidence': ('script_conf', float), 63 | } 64 | 65 | 66 | class Output: 67 | BYTES = 'bytes' 68 | DATAFRAME = 'data.frame' 69 | DICT = 'dict' 70 | STRING = 'string' 71 | 72 | 73 | class PandasNotSupported(EnvironmentError): 74 | def __init__(self): 75 | super().__init__('Missing pandas package') 76 | 77 | 78 | class TesseractError(RuntimeError): 79 | def __init__(self, status, message): 80 | self.status = status 81 | self.message = message 82 | self.args = (status, message) 83 | 84 | 85 | class TesseractNotFoundError(EnvironmentError): 86 | def __init__(self): 87 | super().__init__( 88 | f"{tesseract_cmd} is not installed or it's not in your PATH." 89 | + ' See README file for more information.', 90 | ) 91 | 92 | 93 | class TSVNotSupported(EnvironmentError): 94 | def __init__(self): 95 | super().__init__( 96 | 'TSV output not supported. Tesseract >= 3.05 required', 97 | ) 98 | 99 | 100 | class ALTONotSupported(EnvironmentError): 101 | def __init__(self): 102 | super().__init__( 103 | 'ALTO output not supported. Tesseract >= 4.1.0 required', 104 | ) 105 | 106 | 107 | def kill(process, code): 108 | process.terminate() 109 | try: 110 | process.wait(1) 111 | except TypeError: # python2 Popen.wait(1) fallback 112 | sleep(1) 113 | except Exception: # python3 subprocess.TimeoutExpired 114 | pass 115 | finally: 116 | process.kill() 117 | process.returncode = code 118 | 119 | 120 | @contextmanager 121 | def timeout_manager(proc, seconds=None): 122 | try: 123 | if not seconds: 124 | yield proc.communicate()[1] 125 | return 126 | 127 | try: 128 | _, error_string = proc.communicate(timeout=seconds) 129 | yield error_string 130 | except subprocess.TimeoutExpired: 131 | kill(proc, -1) 132 | raise RuntimeError('Tesseract process timeout') 133 | finally: 134 | proc.stdin.close() 135 | proc.stdout.close() 136 | proc.stderr.close() 137 | 138 | 139 | def run_once(func): 140 | @wraps(func) 141 | def wrapper(*args, **kwargs): 142 | if wrapper._result is wrapper: 143 | wrapper._result = func(*args, **kwargs) 144 | return wrapper._result 145 | 146 | wrapper._result = wrapper 147 | return wrapper 148 | 149 | 150 | def get_errors(error_string): 151 | return ' '.join( 152 | line for line in error_string.decode(DEFAULT_ENCODING).splitlines() 153 | ).strip() 154 | 155 | 156 | def cleanup(temp_name): 157 | """Tries to remove temp files by filename wildcard path.""" 158 | for filename in iglob(temp_name + '*' if temp_name else temp_name): 159 | try: 160 | remove(filename) 161 | except OSError as e: 162 | if e.errno != ENOENT: 163 | raise e 164 | 165 | 166 | def prepare(image): 167 | if numpy_installed and isinstance(image, ndarray): 168 | image = Image.fromarray(image) 169 | 170 | if not isinstance(image, Image.Image): 171 | raise TypeError('Unsupported image object') 172 | 173 | extension = 'PNG' if not image.format else image.format 174 | if extension not in SUPPORTED_FORMATS: 175 | raise TypeError('Unsupported image format/type') 176 | 177 | if 'A' in image.getbands(): 178 | # discard and replace the alpha channel with white background 179 | background = Image.new(RGB_MODE, image.size, (255, 255, 255)) 180 | background.paste(image, (0, 0), image.getchannel('A')) 181 | image = background 182 | 183 | image.format = extension 184 | return image, extension 185 | 186 | 187 | @contextmanager 188 | def save(image): 189 | try: 190 | with NamedTemporaryFile(prefix='tess_', delete=False) as f: 191 | if isinstance(image, str): 192 | yield f.name, realpath(normpath(normcase(image))) 193 | return 194 | image, extension = prepare(image) 195 | input_file_name = f.name + extsep + extension 196 | image.save(input_file_name, format=image.format) 197 | yield f.name, input_file_name 198 | finally: 199 | cleanup(f.name) 200 | 201 | 202 | def subprocess_args(include_stdout=True): 203 | # See https://github.com/pyinstaller/pyinstaller/wiki/Recipe-subprocess 204 | # for reference and comments. 205 | 206 | kwargs = { 207 | 'stdin': subprocess.PIPE, 208 | 'stderr': subprocess.PIPE, 209 | 'startupinfo': None, 210 | 'env': environ, 211 | } 212 | 213 | if hasattr(subprocess, 'STARTUPINFO'): 214 | kwargs['startupinfo'] = subprocess.STARTUPINFO() 215 | kwargs['startupinfo'].dwFlags |= subprocess.STARTF_USESHOWWINDOW 216 | kwargs['startupinfo'].wShowWindow = subprocess.SW_HIDE 217 | 218 | if include_stdout: 219 | kwargs['stdout'] = subprocess.PIPE 220 | else: 221 | kwargs['stdout'] = subprocess.DEVNULL 222 | 223 | return kwargs 224 | 225 | 226 | def run_tesseract( 227 | input_filename, 228 | output_filename_base, 229 | extension, 230 | lang, 231 | config='', 232 | nice=0, 233 | timeout=0, 234 | ): 235 | cmd_args = [] 236 | 237 | if not sys.platform.startswith('win32') and nice != 0: 238 | cmd_args += ('nice', '-n', str(nice)) 239 | 240 | cmd_args += (tesseract_cmd, input_filename, output_filename_base) 241 | 242 | if lang is not None: 243 | cmd_args += ('-l', lang) 244 | 245 | if config: 246 | cmd_args += shlex.split(config) 247 | 248 | if extension and extension not in {'box', 'osd', 'tsv', 'xml'}: 249 | cmd_args.append(extension) 250 | 251 | try: 252 | proc = subprocess.Popen(cmd_args, **subprocess_args()) 253 | except OSError as e: 254 | if e.errno != ENOENT: 255 | raise e 256 | raise TesseractNotFoundError() 257 | 258 | with timeout_manager(proc, timeout) as error_string: 259 | if proc.returncode: 260 | raise TesseractError(proc.returncode, get_errors(error_string)) 261 | 262 | 263 | def run_and_get_output( 264 | image, 265 | extension='', 266 | lang=None, 267 | config='', 268 | nice=0, 269 | timeout=0, 270 | return_bytes=False, 271 | ): 272 | 273 | with save(image) as (temp_name, input_filename): 274 | kwargs = { 275 | 'input_filename': input_filename, 276 | 'output_filename_base': temp_name, 277 | 'extension': extension, 278 | 'lang': lang, 279 | 'config': config, 280 | 'nice': nice, 281 | 'timeout': timeout, 282 | } 283 | 284 | run_tesseract(**kwargs) 285 | filename = kwargs['output_filename_base'] + extsep + extension 286 | with open(filename, 'rb') as output_file: 287 | if return_bytes: 288 | return output_file.read() 289 | return output_file.read().decode(DEFAULT_ENCODING) 290 | 291 | 292 | def file_to_dict(tsv, cell_delimiter, str_col_idx): 293 | result = {} 294 | rows = [row.split(cell_delimiter) for row in tsv.strip().split('\n')] 295 | if len(rows) < 2: 296 | return result 297 | 298 | header = rows.pop(0) 299 | length = len(header) 300 | if len(rows[-1]) < length: 301 | # Fixes bug that occurs when last text string in TSV is null, and 302 | # last row is missing a final cell in TSV file 303 | rows[-1].append('') 304 | 305 | if str_col_idx < 0: 306 | str_col_idx += length 307 | 308 | for i, head in enumerate(header): 309 | result[head] = list() 310 | for row in rows: 311 | if len(row) <= i: 312 | continue 313 | 314 | val = row[i] 315 | if row[i].isdigit() and i != str_col_idx: 316 | val = int(row[i]) 317 | result[head].append(val) 318 | 319 | return result 320 | 321 | 322 | def is_valid(val, _type): 323 | if _type is int: 324 | return val.isdigit() 325 | 326 | if _type is float: 327 | try: 328 | float(val) 329 | return True 330 | except ValueError: 331 | return False 332 | 333 | return True 334 | 335 | 336 | def osd_to_dict(osd): 337 | return { 338 | OSD_KEYS[kv[0]][0]: OSD_KEYS[kv[0]][1](kv[1]) 339 | for kv in (line.split(': ') for line in osd.split('\n')) 340 | if len(kv) == 2 and is_valid(kv[1], OSD_KEYS[kv[0]][1]) 341 | } 342 | 343 | 344 | @run_once 345 | def get_languages(config=''): 346 | cmd_args = [tesseract_cmd, '--list-langs'] 347 | if config: 348 | cmd_args += shlex.split(config) 349 | 350 | try: 351 | result = subprocess.run( 352 | cmd_args, 353 | stdout=subprocess.PIPE, 354 | stderr=subprocess.STDOUT, 355 | ) 356 | except OSError: 357 | raise TesseractNotFoundError() 358 | 359 | # tesseract 3.x 360 | if result.returncode not in (0, 1): 361 | raise TesseractNotFoundError() 362 | 363 | languages = [] 364 | if result.stdout: 365 | for line in result.stdout.decode(DEFAULT_ENCODING).split(linesep): 366 | lang = line.strip() 367 | if LANG_PATTERN.match(lang): 368 | languages.append(lang) 369 | 370 | return languages 371 | 372 | 373 | @run_once 374 | def get_tesseract_version(): 375 | """ 376 | Returns LooseVersion object of the Tesseract version 377 | """ 378 | try: 379 | output = subprocess.check_output( 380 | [tesseract_cmd, '--version'], 381 | stderr=subprocess.STDOUT, 382 | env=environ, 383 | stdin=subprocess.DEVNULL, 384 | ) 385 | except OSError: 386 | raise TesseractNotFoundError() 387 | 388 | raw_version = output.decode(DEFAULT_ENCODING) 389 | version = raw_version.lstrip(string.printable[10:]) 390 | 391 | try: 392 | loose_version = LooseVersion(version) 393 | assert loose_version > '0' 394 | except AttributeError: 395 | raise SystemExit(f'Invalid tesseract version: "{raw_version}"') 396 | 397 | return loose_version 398 | 399 | 400 | def image_to_string( 401 | image, 402 | lang=None, 403 | config='', 404 | nice=0, 405 | output_type=Output.STRING, 406 | timeout=0, 407 | ): 408 | """ 409 | Returns the result of a Tesseract OCR run on the provided image to string 410 | """ 411 | args = [image, 'txt', lang, config, nice, timeout] 412 | 413 | return { 414 | Output.BYTES: lambda: run_and_get_output(*(args + [True])), 415 | Output.DICT: lambda: {'text': run_and_get_output(*args)}, 416 | Output.STRING: lambda: run_and_get_output(*args), 417 | }[output_type]() 418 | 419 | 420 | def image_to_pdf_or_hocr( 421 | image, 422 | lang=None, 423 | config='', 424 | nice=0, 425 | extension='pdf', 426 | timeout=0, 427 | ): 428 | """ 429 | Returns the result of a Tesseract OCR run on the provided image to pdf/hocr 430 | """ 431 | 432 | if extension not in {'pdf', 'hocr'}: 433 | raise ValueError(f'Unsupported extension: {extension}') 434 | args = [image, extension, lang, config, nice, timeout, True] 435 | 436 | return run_and_get_output(*args) 437 | 438 | 439 | def image_to_alto_xml( 440 | image, 441 | lang=None, 442 | config='', 443 | nice=0, 444 | timeout=0, 445 | ): 446 | """ 447 | Returns the result of a Tesseract OCR run on the provided image to ALTO XML 448 | """ 449 | 450 | if get_tesseract_version() < '4.1.0': 451 | raise ALTONotSupported() 452 | 453 | config = f'-c tessedit_create_alto=1 {config.strip()}' 454 | args = [image, 'xml', lang, config, nice, timeout, True] 455 | 456 | return run_and_get_output(*args) 457 | 458 | 459 | def image_to_boxes( 460 | image, 461 | lang=None, 462 | config='', 463 | nice=0, 464 | output_type=Output.STRING, 465 | timeout=0, 466 | ): 467 | """ 468 | Returns string containing recognized characters and their box boundaries 469 | """ 470 | config = f'{config.strip()} batch.nochop makebox' 471 | args = [image, 'box', lang, config, nice, timeout] 472 | 473 | return { 474 | Output.BYTES: lambda: run_and_get_output(*(args + [True])), 475 | Output.DICT: lambda: file_to_dict( 476 | f'char left bottom right top page\n{run_and_get_output(*args)}', 477 | ' ', 478 | 0, 479 | ), 480 | Output.STRING: lambda: run_and_get_output(*args), 481 | }[output_type]() 482 | 483 | 484 | def get_pandas_output(args, config=None): 485 | if not pandas_installed: 486 | raise PandasNotSupported() 487 | 488 | kwargs = {'quoting': QUOTE_NONE, 'sep': '\t'} 489 | try: 490 | kwargs.update(config) 491 | except (TypeError, ValueError): 492 | pass 493 | 494 | return pd.read_csv(BytesIO(run_and_get_output(*args)), **kwargs) 495 | 496 | 497 | def image_to_data( 498 | image, 499 | lang=None, 500 | config='', 501 | nice=0, 502 | output_type=Output.STRING, 503 | timeout=0, 504 | pandas_config=None, 505 | ): 506 | """ 507 | Returns string containing box boundaries, confidences, 508 | and other information. Requires Tesseract 3.05+ 509 | """ 510 | 511 | if get_tesseract_version() < '3.05': 512 | raise TSVNotSupported() 513 | 514 | config = f'-c tessedit_create_tsv=1 {config.strip()}' 515 | args = [image, 'tsv', lang, config, nice, timeout] 516 | 517 | return { 518 | Output.BYTES: lambda: run_and_get_output(*(args + [True])), 519 | Output.DATAFRAME: lambda: get_pandas_output( 520 | args + [True], 521 | pandas_config, 522 | ), 523 | Output.DICT: lambda: file_to_dict(run_and_get_output(*args), '\t', -1), 524 | Output.STRING: lambda: run_and_get_output(*args), 525 | }[output_type]() 526 | 527 | 528 | def image_to_osd( 529 | image, 530 | lang='osd', 531 | config='', 532 | nice=0, 533 | output_type=Output.STRING, 534 | timeout=0, 535 | ): 536 | """ 537 | Returns string containing the orientation and script detection (OSD) 538 | """ 539 | psm_dash = '' if get_tesseract_version() < '3.05' else '-' 540 | config = f'{psm_dash}-psm 0 {config.strip()}' 541 | args = [image, 'osd', lang, config, nice, timeout] 542 | 543 | return { 544 | Output.BYTES: lambda: run_and_get_output(*(args + [True])), 545 | Output.DICT: lambda: osd_to_dict(run_and_get_output(*args)), 546 | Output.STRING: lambda: run_and_get_output(*args), 547 | }[output_type]() 548 | 549 | 550 | def main(): 551 | if len(sys.argv) == 2: 552 | filename, lang = sys.argv[1], None 553 | elif len(sys.argv) == 4 and sys.argv[1] == '-l': 554 | filename, lang = sys.argv[3], sys.argv[2] 555 | else: 556 | print('Usage: pytesseract [-l lang] input_file\n', file=sys.stderr) 557 | return 2 558 | 559 | try: 560 | with Image.open(filename) as img: 561 | print(image_to_string(img, lang=lang)) 562 | except TesseractNotFoundError as e: 563 | print(f'{str(e)}\n', file=sys.stderr) 564 | return 1 565 | except OSError as e: 566 | print(f'{type(e).__name__}: {e}', file=sys.stderr) 567 | return 1 568 | 569 | 570 | if __name__ == '__main__': 571 | exit(main()) 572 | -------------------------------------------------------------------------------- /rpc.py: -------------------------------------------------------------------------------- 1 | from pypresence import Presence 2 | import time 3 | import update_stat 4 | import os 5 | 6 | global char 7 | 8 | client_id = "860796517240274994" 9 | rich_presence = Presence(client_id) 10 | 11 | def connect(): 12 | return rich_presence.connect() 13 | 14 | def connect_loop(lang, retries=0): 15 | if retries > 10: 16 | return 17 | try: 18 | connect() 19 | except: 20 | print("Error connecting to Discord") 21 | time.sleep(10) 22 | retries += 1 23 | connect_loop(lang, retries) 24 | else: 25 | update_loop(lang) 26 | 27 | def get_data(): 28 | return( 29 | {'state': "目前对立占上风", 30 | 'small_image': "grass_2", 31 | 'large_image': "grass_1", 32 | 'large_text': "Tairitsu", 33 | 'small_text': "Hikari", 34 | 'details': "光和对立正在打架", 35 | 'buttons': [{"label": "去劝架", "url": "http://127.0.0.1:11451/qwq"}, {"label": "我也要和她们打架!", "url": "http://127.0.0.1:11451/owo"}] 36 | } 37 | ) 38 | 39 | def update_loop(lang): 40 | global char 41 | start_time = int(time.time()) 42 | try: 43 | model = str(os.popen("adb -d shell getprop ro.product.model").read()) 44 | 45 | while True: 46 | rpc_data = update_stat.start(lang) 47 | if(rpc_data['details'] == "Device"): 48 | det = model.replace('\n', '') 49 | else: 50 | det = "Score:" + rpc_data['details'] 51 | 52 | rich_presence.update(state = rpc_data['state'], 53 | small_image = char, 54 | large_image = rpc_data['large_image'], 55 | large_text = rpc_data['large_text'], 56 | #small_text = rpc_data['small_text'], 57 | details = det, 58 | #buttons = rpc_data['buttons'], 59 | start = start_time) 60 | print("状态已更新:" + det + ' - ' + rpc_data['state']) 61 | time.sleep(5) 62 | except Exception as sb: 63 | print(sb) 64 | rich_presence.clear() 65 | time.sleep(5) 66 | update_loop(lang) 67 | 68 | 69 | if __name__ == '__main__': 70 | tstat = update_stat.check_run() 71 | if(tstat == "ok"): 72 | print("您的Arcaea系统语言是(1:非日语 2:日本語):") 73 | lang = str(input()) 74 | if(lang == '2'): 75 | print("注意:日语部分歌曲识别准确率较低") 76 | print("输入角色编号:") 77 | char = str(input()) + "_icon" 78 | 79 | try: 80 | print("开始运行") 81 | connect_loop(lang) 82 | except KeyboardInterrupt: 83 | print("服务停止") 84 | 85 | else: 86 | print(tstat) 87 | -------------------------------------------------------------------------------- /run.bat: -------------------------------------------------------------------------------- 1 | python rpc.py 2 | pause -------------------------------------------------------------------------------- /sc_0c9b5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/sc_0c9b5.png -------------------------------------------------------------------------------- /temp/empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/temp/empty -------------------------------------------------------------------------------- /testjpn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinosk6/Arcaea_Discord_Rich_Presence/9fa422a42ac8f267a449d62add2122afa1af7fd4/testjpn.png -------------------------------------------------------------------------------- /update_stat.py: -------------------------------------------------------------------------------- 1 | import os, time 2 | import random, string 3 | import catch_stat 4 | import subprocess 5 | 6 | def popen(com, is_out = False): 7 | ex = subprocess.Popen(com, stdout=subprocess.PIPE, shell=True) 8 | out = 'f' 9 | try: 10 | out = ex.stdout.read().decode("GBK") 11 | except: 12 | out = ex.stdout.read().decode("utf-8") 13 | return out 14 | 15 | def generate_randstring(num = 5): 16 | value = ''.join(random.sample(string.ascii_letters + string.digits, num)) 17 | return(value) 18 | 19 | def check_run(): 20 | res = os.popen("adb shell \"dumpsys window | grep mCurrentFocus\"") 21 | now_run = res.read() 22 | #print(now_run) 23 | if("moe.low.arc" not in now_run): 24 | if("mCurrentFocus" in now_run): 25 | return("未检测到Arcaea运行") 26 | elif("no devices" in now_run): 27 | return("您没有连接设备,或者没有打开USB调试") 28 | elif("adb" in now_run): 29 | return("您的电脑没有安装ADB") 30 | 31 | else: 32 | return("ok") 33 | 34 | def start(lang): 35 | #print("您的Arcaea系统语言是(1:非日语 2:日本語):") 36 | #lang = str(input()) 37 | #if(lang == '2'): 38 | # print("注意:日语部分歌曲识别准确率较低") 39 | 40 | #tstat = check_run() 41 | #if(tstat == "ok"): 42 | #while True: 43 | iname = generate_randstring(5) 44 | fstat = popen("adb shell /system/bin/screencap -p /sdcard/%s.png" % iname) 45 | fstat = popen("adb pull /sdcard/%s.png /temp/%s.png" % (iname, iname)) 46 | fstat = popen("adb shell rm /sdcard/%s.png" % iname) 47 | 48 | if(os.path.isfile("/temp/%s.png" % iname) == False): 49 | print("游玩数据获取失败") 50 | else: 51 | now_info = catch_stat.stat_identify(("/temp/%s.png" % iname), lang) 52 | now_stat = now_info[0] 53 | now_score = now_info[1] 54 | os.remove("/temp/%s.png" % iname) 55 | #print(now_stat) 56 | 57 | #time.sleep(2) 58 | if(now_stat != "In Menu"): 59 | now_stat = "Playing " + now_stat 60 | 61 | if(now_score == "0"): 62 | now_score = "Device" 63 | else: 64 | try: 65 | now_score = str("%.8d" % int(now_score)) 66 | now_score = now_score[0:2] + '\'' + now_score[2:5] + '\'' + now_score[5:8] 67 | except Exception as sb: 68 | print(sb) 69 | now_score = "Device" 70 | 71 | return( 72 | {'state': now_stat, 73 | 'small_image': "grass_2", 74 | 'large_image': "main_icon", 75 | 'large_text': "Arcaea", 76 | 'small_text': "Hikari", 77 | 'details': now_score, 78 | 'buttons': [{"label": "去劝架", "url": "http://127.0.0.1:11451/qwq"}, {"label": "我也要和她们打架!", "url": "http://127.0.0.1:11451/owo"}] 79 | } 80 | ) 81 | 82 | #else: 83 | #print(tstat) 84 | #return(None) 85 | --------------------------------------------------------------------------------