Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.99 KB | None | 0 0
  1. from fuzzywuzzy import fuzz, process
  2. import os
  3. import ConfigParser
  4. from PIL import Image, ImageFilter, ImageOps, ImageEnhance
  5. from pytesseract import image_to_string as tess
  6. from collections import namedtuple
  7. import time
  8. import requests
  9. import json
  10. import psycopg2
  11.  
  12. def getresinfo(im):
  13.     config = ConfigParser.SafeConfigParser()
  14.     config.read("./libs/resolution_" + str(im.size[0]) + "x" + str(im.size[1]) + ".ini")
  15.     resdata = {}
  16.  
  17.     for section in config.sections():
  18.         resdata[section] = {}
  19.         for item in config.items(section):
  20.             resdata[section][item[0]] = item[1]
  21.     return resdata
  22.  
  23. def preprocess(img):
  24.     temp = img
  25.     temp = ImageOps.invert(temp).convert(mode="L").point(lambda p: p > 30 and 255)
  26.     return temp
  27.  
  28. def getrowelement(section):
  29.     global resdata, row, temp
  30.  
  31.     x1 = int(resdata[section]["x1"])
  32.     x2 = int(resdata[section]["x2"])
  33.     rowheight = int(resdata["RowHeight"]["height"])
  34.     y1 = int(resdata["Rows"][row])
  35.  
  36.     box = [x1, y1, x2, y1+rowheight]
  37.     #temp.crop(box).save("./screenshots/debug/5ApFK8q_" + row + ".jpg")
  38.     return tess(temp.crop(box), config="-psm 6" )
  39.  
  40. def getfileleveldata():
  41.     pass
  42.  
  43. def getrowleveldata():
  44.     pass
  45.  
  46. def createmechlistfile():
  47.     f1=open('./mechlist', 'w+')
  48.    
  49.     for x in mechlist():
  50.         print >>f1, x
  51.  
  52. def mechlist():
  53.  
  54.     url = "http://mwo.smurfy-net.de/api/data/mechs"
  55.     full_json = json.loads(requests.get(url).text)
  56.     mechs = []
  57.    
  58.     for key,value in full_json.iteritems():
  59.         mechs.append(value["translated_short_name"])
  60.  
  61.     return sorted(mechs)
  62.  
  63. def main():
  64.     global resdata, row, temp
  65.  
  66.     files = os.listdir('./../../screenshots/Failoe')
  67.    
  68.     start_time = time.time()
  69.  
  70.     for file in files:
  71.    
  72.         filepath = "./../../screenshots/Failoe/"+file
  73.         print filepath
  74.         im = Image.open(filepath)
  75.         temp = preprocess(im)
  76.    
  77.         resdata = getresinfo(im)
  78.  
  79.         temp = preprocess(im)
  80.  
  81.         for row in resdata["Rows"]:
  82.             player = getrowelement("Player")
  83.             mech = getrowelement("Mech")
  84.             status = getrowelement("Status")
  85.             score = getrowelement("Matchscore")
  86.             kills = getrowelement("Kills")
  87.             assists = getrowelement("Assists")
  88.             damage = getrowelement("Damage")
  89.             faction = getrowelement("Faction")
  90.             ping = getrowelement("Ping")
  91.            
  92.             print time.time(), faction, player, mech, "Status:", status, "Score:", score, "Kills: ", kills, "Assists:", assists, "Damage:", damage, "Ping:", ping
  93.         print time.time() - start_time     
  94.  
  95. def collectinitialdata():
  96.     with open('./libs/maps.txt', 'r') as f:
  97.         mapnames = [line.strip() for line in f]
  98.     with open('./libs/modes.txt', 'r') as f:
  99.         modes = [line.strip() for line in f]
  100.     with open('./libs/mechlist', 'r') as f:
  101.         mechs = [line.strip() for line in f]
  102.     return (mapnames, modes, mechs)
  103.  
  104. def get_processingtime():
  105.     return time.time()
  106.  
  107. def get_map():
  108.     global resdata, temp, mapnames
  109.     x1 = int(resdata["Map"]["x1"])
  110.     x2 = int(resdata["Map"]["x2"])
  111.     y1 = int(resdata["Map"]["y1"])
  112.     y2 = int(resdata["Map"]["y2"])
  113.     box = [x1, y1, x2, y2]
  114.     tessmap = tess(temp.crop(box), config="-psm 6" )
  115.     fuzzmap = process.extractOne(tessmap, mapnames)[0]
  116.     distratio = process.extractOne(tessmap, mapnames)[1]
  117.  
  118.     if distratio > 80:
  119.         return fuzzmap
  120.     else:
  121.         return "Failed to identify: " + tessmap
  122.         #Abort needed
  123.  
  124. def get_mode():
  125.     global resdata, modes, im
  126.     x1 = int(resdata["Mode"]["x1"])
  127.     x2 = int(resdata["Mode"]["x2"])
  128.     y1 = int(resdata["Mode"]["y1"])
  129.     y2 = int(resdata["Mode"]["y2"])
  130.     box = [x1, y1, x2, y2]
  131.     temp = im.crop(box)
  132.     tempmode = ImageOps.invert(temp).convert(mode="L").point(lambda p: p > 80 and 255)
  133.     tessmode = tess(tempmode, config="-psm 6" ).replace("GAME MODE:","")
  134.     fuzzmode = process.extractOne(tessmode, modes)[0]
  135.     distratio = process.extractOne(tessmode, modes)[1]
  136.  
  137.     if distratio > 80:
  138.         return fuzzmode
  139.     else:
  140.         level = 75
  141.         while level > 20:
  142.             tempmode = ImageOps.invert(temp).convert(mode="L").point(lambda p: p > level and 255)
  143.             tessmode = tess(tempmode, config="-psm 6" ).replace("GAME MODE:","")
  144.             fuzzmode = process.extractOne(tessmode, modes)[0]
  145.             distratio = process.extractOne(tessmode, modes)[1]
  146.             level -= 5
  147.             if distratio > 80:
  148.                 return fuzzmode
  149.         else:
  150.             return "Failed to identify: " + tessmode
  151.             #Abort needed
  152.    
  153.  
  154. def get_match_time():
  155.     global resdata, im
  156.     x1 = int(resdata["Time"]["x1"])
  157.     x2 = int(resdata["Time"]["x2"])
  158.     y1 = int(resdata["Time"]["y1"])
  159.     y2 = int(resdata["Time"]["y2"])
  160.     box = [x1, y1, x2, y2]
  161.     temp = im.crop(box)
  162.     temptime = ImageOps.invert(temp).convert(mode="L").point(lambda p: p > 80 and 255)
  163.     tesstime = tess(temptime, config="-psm 6" )
  164.  
  165.     return tesstime
  166.  
  167. def get_team():
  168.     global row
  169.  
  170.     rowint = int(row.replace("row",""))
  171.  
  172.     if rowint <= 12:
  173.         team = "Team A"
  174.     elif rowint >= 12:
  175.         team = "Team B"
  176.     else:
  177.         pass #Abort
  178.  
  179.     return team
  180.  
  181. def get_match_outcome():
  182.     global row
  183.  
  184.     rowint = int(row.replace("row",""))
  185.  
  186.     if rowint <= 12:
  187.         outcome = "Victory"
  188.     elif rowint >= 12:
  189.         outcome = "Defeat"
  190.     else:
  191.         pass #Abort
  192.  
  193.     return outcome
  194.  
  195. def get_lance():
  196.     global row
  197.  
  198.     rowint = int(row.replace("row",""))
  199.  
  200.     if rowint in [1,2,3,4,13,14,15,16]:
  201.         lance = "Alpha"
  202.     elif rowint in [5,6,7,8,17,18,19,20]:
  203.         lance = "Bravo"
  204.     elif rowint in [9,10,11,12,21,22,23,24]:
  205.         lance = "Charlie"
  206.  
  207.     return lance
  208.  
  209. def get_faction():
  210.     global resdata, row, temp
  211.  
  212.     x1 = int(resdata["Faction"]["x1"])
  213.     x2 = int(resdata["Faction"]["x2"])
  214.     rowheight = int(resdata["RowHeight"]["height"])
  215.     y1 = int(resdata["Rows"][row])
  216.  
  217.     box = [x1, y1, x2, y1+rowheight]
  218.  
  219.     tessfac = tess(temp.crop(box), config="-psm 6" )
  220.     trimfac = tessfac[1:-1]
  221.  
  222.     return trimfac
  223.  
  224. def get_pilot_name():
  225.     global resdata, row, temp
  226.  
  227.     x1 = int(resdata["Pilot"]["x1"])
  228.     x2 = int(resdata["Pilot"]["x2"])
  229.     rowheight = int(resdata["RowHeight"]["height"])
  230.     y1 = int(resdata["Rows"][row])
  231.  
  232.     box = [x1, y1, x2, y1+rowheight]
  233.  
  234.     tessplayer = tess(temp.crop(box), config="-psm 6" )
  235.  
  236.     return tessplayer
  237.  
  238. def get_mech():
  239.     global resdata, temp, row, mechs, im
  240.     x1 = int(resdata["Mech"]["x1"])
  241.     x2 = int(resdata["Mech"]["x2"])
  242.     y1 = int(resdata["Rows"][row])
  243.     y2 = int(resdata["RowHeight"]["height"]) + y1
  244.     box = [x1, y1, x2, y2]
  245.     tessmech = tess(temp.crop(box), config="-psm 6" )
  246.     fuzzmech = process.extractOne(tessmech, mechs)[0]
  247.     distratio = process.extractOne(tessmech, mechs)[1]
  248.  
  249.     if distratio > 80:
  250.         return fuzzmech
  251.     else:
  252.         level = 100
  253.         tempim = im.crop(box)
  254.         while level > 20:
  255.             tempmech = ImageOps.invert(tempim).convert(mode="L").point(lambda p: p > level and 255)
  256.             tessmech = tess(tempmech, config="-psm 6" )
  257.             fuzzmech = process.extractOne(tessmech, modes)[0]
  258.             distratio = process.extractOne(tessmech, modes)[1]
  259.             level -= 5
  260.             if distratio > 80:
  261.                 return fuzzmech
  262.         else:
  263.             return "Failed to identify: " + tessmech
  264.             #Abort needed
  265.    
  266. def get_status():
  267.     global resdata, temp, row, im
  268.     possible_statuses = ["Alive", "Dead", "Disconnected"]
  269.     x1 = int(resdata["Status"]["x1"])
  270.     x2 = int(resdata["Status"]["x2"])
  271.     y1 = int(resdata["Rows"][row])
  272.     y2 = int(resdata["RowHeight"]["height"]) + y1
  273.     box = [x1, y1, x2, y2]
  274.     tessstatus = tess(temp.crop(box), config="-psm 6" )
  275.     fuzzstatus = process.extractOne(tessstatus, possible_statuses)[0]
  276.     distratio = process.extractOne(tessstatus, possible_statuses)[1]
  277.  
  278.     if distratio > 80:
  279.         return fuzzstatus
  280.     else:
  281.         level = 230
  282.         tempim = im.crop(box)
  283.         while level > 150:
  284.             tempstatus = ImageOps.invert(tempim.convert(mode="L")).point(lambda p: p > level and 255)
  285.             tessstatus = tess(tempstatus, config="-psm 6" )
  286.             fuzzstatus = process.extractOne(tessstatus, possible_statuses)[0]
  287.             distratio = process.extractOne(tessstatus, possible_statuses)[1]
  288.             level -= 5
  289.             if distratio > 80:
  290.                 return fuzzstatus
  291.         else:
  292.             return "Failed to identify: " + tessstatus
  293.             #Abort needed
  294.  
  295. def get_match_score():
  296.     global resdata, row, temp
  297.  
  298.     x1 = int(resdata["Matchscore"]["x1"])
  299.     x2 = int(resdata["Matchscore"]["x2"])
  300.     rowheight = int(resdata["RowHeight"]["height"])
  301.     y1 = int(resdata["Rows"][row])
  302.  
  303.     box = [x1, y1, x2, y1+rowheight]
  304.  
  305.     tessscore = tess(temp.crop(box), config="-psm 6" )
  306.  
  307.     return tessscore
  308.  
  309. def get_kills():
  310.     pass
  311. def get_assists():
  312.     pass
  313. def get_damage():
  314.     pass
  315. def get_ping():
  316.     pass
  317.  
  318. def get_row_value(section):
  319.     global resdata, row, temp
  320.  
  321.     x1 = int(resdata[section]["x1"])
  322.     x2 = int(resdata[section]["x2"])
  323.     rowheight = int(resdata["RowHeight"]["height"])
  324.     y1 = int(resdata["Rows"][row])
  325.  
  326.     box = [x1, y1, x2, y1+rowheight]
  327.  
  328.     tessvalue = tess(temp.crop(box), config="-psm 6" )
  329.  
  330.     return tessvalue
  331.  
  332. def isteamstats(image):
  333.     global resdata
  334.  
  335.     x1 = int(resdata["PilotLabel"]["x1"])
  336.     x2 = int(resdata["PilotLabel"]["x2"])
  337.     y1 = int(resdata["PilotLabel"]["y1"])
  338.     y2 = int(resdata["PilotLabel"]["y2"])
  339.  
  340.     box = [x1, y1, x2, y2]
  341.  
  342.     filtercheck = ImageOps.invert(image.crop(box)).convert(mode="L").point(lambda p: p > 30 and 255)
  343.  
  344.     tessfilter = tess(filtercheck, config="-psm 6" )
  345.     fuzzratio = fuzz.ratio(tessfilter, "PILOT NAME")
  346.  
  347.     if fuzzratio > 80:
  348.         return True
  349.     else:
  350.         return False
  351.  
  352. def pushdata():
  353.     global mapname, mode, matchtime, team, outcome, matchid, lance, faction, pilot, mech, status, matchscore, kills, assists, damage, ping
  354.  
  355.     conn = psycopg2.connect(database="gamedata", user="pyuser", password="r4inbows!", host="www.objectivelyperfect.com", port="5432")
  356.     cur = conn.cursor()
  357.     cur.execute(
  358.         """INSERT INTO ocrdata (matchid, processingtime, mapname, mode, matchtime, team, outcome, lance, faction, pilot, mech, status, matchscore, kills, assists, damage, ping) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);""",
  359.         (matchid, time.time(), mapname, mode, matchtime, team, outcome, lance, faction, pilot, mech, status, matchscore, kills, assists, damage, ping))
  360.     conn.commit()
  361.     cur.close()
  362.     conn.close()
  363.  
  364.  
  365. def create_table():
  366.     conn = psycopg2.connect(database="gamedata", user="pyuser", password="r4inbows!", host="www.objectivelyperfect.com", port="5432")
  367.     cur = conn.cursor()
  368.     #cur.execute("DROP TABLE ocrdata;")
  369.     cur.execute("CREATE TABLE ocrdata (matchid numeric, processingtime numeric, mapname varchar, mode varchar, matchtime varchar, team varchar, outcome varchar, lance varchar, faction varchar, pilot varchar, mech varchar, status varchar, matchscore int, kills int, assists int, damage int, ping int);")
  370.     conn.commit()
  371.     cur.close()
  372.     conn.close()
  373.  
  374.  
  375.  
  376. def test():
  377.     global resdata, temp, mapnames, modes, mechs, im, row, matchid, mapname, mode, matchtime, team, outcome, lance, faction, pilot, mech, status, matchscore, kills, assists, damage, ping
  378.     files = os.listdir('./../../Screenshots/Failoe/')
  379.     (mapnames, modes, mechs) = collectinitialdata()
  380.  
  381.     start_time = time.time()
  382.  
  383.     for file in files:
  384.         try:
  385.             matchid = time.time()
  386.             filepath = "./../../Screenshots/Failoe/"+file
  387.             im = Image.open(filepath)
  388.             resdata = getresinfo(im)
  389.             if isteamstats(im):
  390.                 temp = preprocess(im)
  391.                 mapname = get_map()
  392.                 mode = get_mode()
  393.                 matchtime = get_match_time()
  394.                 for row in resdata["Rows"]:
  395.                     team = get_team()
  396.                     outcome = get_match_outcome()
  397.                     lance = get_lance()
  398.                     faction = get_faction()
  399.                     pilot = get_pilot_name()
  400.                     mech =  get_mech()
  401.                     status = get_status()
  402.                     matchscore = get_row_value("Matchscore")
  403.                     kills = get_row_value("Kills")
  404.                     assists = get_row_value("Assists")
  405.                     damage = get_row_value("Damage")
  406.                     ping = get_row_value("Ping")
  407.                     #start test formatting
  408.                     while len(lance) <= 8:
  409.                         lance+=" "
  410.                     while len(faction) <= 7:
  411.                         faction+=" "
  412.                     while len(outcome) <=6:
  413.                         outcome+=" "
  414.                     while len(pilot) <= 16:
  415.                         pilot+=" "
  416.                     while len(mech) <= 12:
  417.                         mech+=" "
  418.                     while len(status) <= 13:
  419.                         status += " "
  420.                     while len(matchscore) <= 4:
  421.                         matchscore += " "
  422.                     while len(kills) <= 3:
  423.                         kills+=" "
  424.                     while len(assists) <= 3:
  425.                         assists+=" "
  426.                     while len(damage) <= 5:
  427.                         damage+=" "            
  428.                     #end test formatting
  429.                     pushdata()
  430.                     print time.time(), mapname, mode, matchtime, team, outcome, lance, faction, pilot, mech, status, matchscore, kills, assists, damage, ping
  431.             else:
  432.                 pass
  433.         except:
  434.             pass
  435. create_table()
  436. test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement