Skip to content

Instantly share code, notes, and snippets.

@eliask
Last active April 27, 2020 13:01
Show Gist options
  • Save eliask/29dc8b11ca08ff5ea51870cfe7adec30 to your computer and use it in GitHub Desktop.
Save eliask/29dc8b11ca08ff5ea51870cfe7adec30 to your computer and use it in GitHub Desktop.
Classifying images with Python and HTML (type o/x for ok/bad)
import http.server
import socketserver
import os, sys, re, glob, shutil
from pathlib import *
PORT = int(sys.argv[1])
def get_known():
try:
known_bad = list({x.strip() for x in open('known_bad.txt').read().strip().split('\n')})
known_good = list({x.strip() for x in open('known_good.txt').read().strip().split('\n')})
except OSError:
known_bad = []; known_good = []
return known_bad, known_good
known_bad, known_good = get_known()
known_all = set(known_bad) | set(known_good)
images = [Path(x) for x in glob.glob('foos/*.jpg') if Path(x).name not in known_all]
class Asd(http.server.SimpleHTTPRequestHandler):
def do_GET(self, *args, **kwargs):
if self.path.startswith('/foos/'):
self.send_response(200)
self.send_header('Content-type','image/jpeg')
self.end_headers()
with open(self.path[1:], 'rb') as fh:
shutil.copyfileobj(fh, self.wfile)
return
ok = self.path.startswith('/ok/')
bad = self.path.startswith('/bad/')
classified_img = self.path.split('/')[-1] if ok or bad else None
known_bad, known_good = get_known()
if classified_img and ok:
print('OK', classified_img)
known_good += [classified_img]
with open('known_good.txt', 'wt') as fh: fh.write('\n'.join(known_good)); fh.write('\n')
if classified_img and bad:
print('BAD', classified_img)
known_bad += [classified_img]
with open('known_bad.txt', 'wt') as fh: fh.write('\n'.join(known_bad)); fh.write('\n')
known_all = set(known_bad) | set(known_good)
global images
if not images:
images[:] = [Path(x) for x in glob.glob('foos/*.jpg') if Path(x).name not in known_all]
if not images:
self.send_response(200)
self.wfile.write(b'All done')
return
img = images[0]
while img.name in known_all:
images = images[1:]
if not images:
self.send_response(200)
self.wfile.write(b'All done')
return
img = images[0]
html = f'''
<html>
<body>
<img src="/{img}" width=1000 height=1000 />
<form id="okform" action="/ok/{img}"></form>
<form id="badform" action="/bad/{img}"></form>
<script>''' + '''
document.addEventListener('keydown', function(e) {
console.log(e)
const ok = e.key === 'o'
const bad = e.key === 'x'
if (ok) okform.submit()
if (bad) badform.submit()
});
</script>
</body>
</html>
'''
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(html.encode('utf-8'))
return
with socketserver.TCPServer(("", PORT), Asd) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment