backend.cgi 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. import os, random, json, statistics, hashlib, datetime
  3. import cgi, cgitb # I like cgi because it was popular when I was born
  4. import maxminddb
  5. import acousticgender
  6. import acousticgender.library.preprocessing as preprocessing
  7. import acousticgender.library.phones as phones
  8. import acousticgender.library.resonance as resonance
  9. settings = acousticgender.library.settings.settings
  10. # Helpers
  11. random_id = lambda: str(random.randint(0, 2**32))
  12. request_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
  13. ################## Form Handling ##################
  14. cgitb.enable()
  15. print("Content-type:text/plain\r\n\r\n")
  16. form = cgi.FieldStorage()
  17. uploaded_file = form.getvalue('recording')
  18. transcript = form.getvalue('transcript')
  19. id = random_id()
  20. tmp_dir = settings['recordings'] + id
  21. praat_output = preprocessing.process(uploaded_file, transcript, tmp_dir)
  22. data = phones.parse(praat_output)
  23. weights = [0.7321428571428571, 0.26785714285714285, 0.0]
  24. resonance.compute_resonance(data, weights)
  25. print(json.dumps(data))
  26. countries = None
  27. if os.path.exists('./countries.mmdb'):
  28. countries = maxminddb.open_database('./countries.mmdb')
  29. # Logging
  30. if settings['logs'] and os.path.exists(settings['logs']):
  31. #try:
  32. ip = os.environ.get('REMOTE_ADDR')
  33. logfile = settings['logs'] + request_date.replace(' ', '_') + '_' + id + '.json'
  34. with open(logfile, 'w') as f:
  35. log_info = {
  36. # Hash the IP so that we can count use by a single user
  37. # without compromising their privacy.
  38. 'country': countries.get(ip)['country']['iso_code'],
  39. 'ua': os.environ.get('HTTP_USER_AGENT'),
  40. 'date': request_date,
  41. 'referrer': form.getvalue('referrer'),
  42. 'lang': form.getvalue('lang'),
  43. 'screen-dimensions' : {
  44. 'width' : form.getvalue('screen-width'),
  45. 'height' : form.getvalue('screen-height'),
  46. }
  47. }
  48. log_info['id'] = hashlib.sha256((
  49. ip + log_info['ua'] + str(log_info['screen-dimensions'])
  50. ).encode('ascii')).hexdigest()
  51. f.write(json.dumps(log_info))
  52. #except:
  53. # pass