Bugfixes in main.py

* Forgotten "\n"
* Very beginning of a web interface
This commit is contained in:
Phyks 2014-04-25 16:53:08 +02:00
parent 5396f1e75b
commit b9f6e145e9
3 changed files with 72 additions and 18 deletions

View File

@ -71,6 +71,7 @@ TODO
A list of ideas and TODO. Don't hesitate to give feedback on the ones you really want or to propose your owns. A list of ideas and TODO. Don't hesitate to give feedback on the ones you really want or to propose your owns.
* Webserver interface
* Various re.compile ? * Various re.compile ?
* check output of subprocesses before it ends * check output of subprocesses before it ends
* Split main.py * Split main.py

40
main.py
View File

@ -1,8 +1,6 @@
#!/usr/bin/env python2 #!/usr/bin/env python2
# -*- coding: utf8 -*- # -*- coding: utf8 -*-
"""
Main app
"""
from __future__ import print_function from __future__ import print_function
import sys import sys
@ -12,7 +10,7 @@ import subprocess
import re import re
import os import os
from isbntools import meta from isbntools import meta
from isbntools.dev.fmt import fmtbib, fmts from isbntools.dev.fmt import fmtbib
try: try:
from cStringIO import StringIO from cStringIO import StringIO
except: except:
@ -39,8 +37,8 @@ def parsed2Bibtex(parsed):
""" """
Convert a single bibtex entry dict to bibtex string Convert a single bibtex entry dict to bibtex string
""" """
bibtex = '@'+parsed['type']+'{'+parsed['id']+"\n" bibtex = '@'+parsed['type']+'{'+parsed['id']+",\n"
for field in [i for i in sorted(parsed) if i not in ['type', 'id']]: for field in [i for i in sorted(parsed) if i not in ['type', 'id']]:
bibtex += "\t"+field+"={"+parsed[field]+"},\n" bibtex += "\t"+field+"={"+parsed[field]+"},\n"
bibtex += "}\n" bibtex += "}\n"
@ -55,6 +53,7 @@ def bibtexAppend(data):
with open(params.folder+'index.bib', 'a') as fh: with open(params.folder+'index.bib', 'a') as fh:
fh.write(parsed2Bibtex(data)+"\n") fh.write(parsed2Bibtex(data)+"\n")
def bibtexRewrite(data): def bibtexRewrite(data):
""" """
Rewrite the bibtex index file. Rewrite the bibtex index file.
@ -89,7 +88,7 @@ def findISBN(src):
extractfull = extractfull[0] extractfull = extractfull[0]
extractISBN = re.search(r"isbn (([0-9]{3}[ -])?[0-9][ -][0-9]{2}[ -][0-9]{6}[ -][0-9])", extractISBN = re.search(r"isbn (([0-9]{3}[ -])?[0-9][ -][0-9]{2}[ -][0-9]{6}[ -][0-9])",
extractfull.lower().replace('Œ', '-')) extractfull.lower().replace('Œ', '-'))
cleanISBN = False cleanISBN = False
if extractISBN: if extractISBN:
@ -169,11 +168,13 @@ def doi2Bib(doi):
_slugify_strip_re = re.compile(r'[^\w\s-]') _slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compile(r'[\s]+') _slugify_hyphenate_re = re.compile(r'[\s]+')
def _slugify(value): def _slugify(value):
""" """
Normalizes string, converts to lowercase, removes non-alpha characters, Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens. and converts spaces to hyphens.
From Django's "django/template/defaultfilters.py". From Django's "django/template/defaultfilters.py".
""" """
import unicodedata import unicodedata
@ -201,10 +202,10 @@ def checkBibtex(filename, bibtex):
bibtex = bibtex.get_entry_dict() bibtex = bibtex.get_entry_dict()
bibtex_name = bibtex.keys()[0] bibtex_name = bibtex.keys()[0]
bibtex = bibtex[bibtex_name] bibtex = bibtex[bibtex_name]
while check.lower() == 'n': while check.lower() == 'n':
fields = [u'type', u'id'] + [i for i in sorted(bibtex) fields = [u'type', u'id'] + [i for i in sorted(bibtex)
if i not in ['id', 'type']] if i not in ['id', 'type']]
for field in fields: for field in fields:
new_value = rawInput(field.capitalize()+" ? ["+bibtex[field]+"] ") new_value = rawInput(field.capitalize()+" ? ["+bibtex[field]+"] ")
@ -218,7 +219,6 @@ def checkBibtex(filename, bibtex):
new_value = rawInput("Value for field "+new_field+" ? ") new_value = rawInput("Value for field "+new_field+" ? ")
bibtex[new_field] = new_value bibtex[new_field] = new_value
print("\nThe bibtex entry for "+filename+" is :") print("\nThe bibtex entry for "+filename+" is :")
print(parsed2Bibtex(bibtex)) print(parsed2Bibtex(bibtex))
check = rawInput("Is it correct ? [Y/n] ") check = rawInput("Is it correct ? [Y/n] ")
@ -239,6 +239,7 @@ def addFile(src, filetype):
if filetype is None: if filetype is None:
warning("Could not determine the DOI or the ISBN for "+src+"." + warning("Could not determine the DOI or the ISBN for "+src+"." +
"Switching to manual entry.") "Switching to manual entry.")
doi_isbn = ''
while doi_isbn not in ['doi', 'isbn']: while doi_isbn not in ['doi', 'isbn']:
doi_isbn = rawInput("DOI / ISBN ? ").lower() doi_isbn = rawInput("DOI / ISBN ? ").lower()
if doi_isbn == 'doi': if doi_isbn == 'doi':
@ -246,12 +247,12 @@ def addFile(src, filetype):
else: else:
isbn = rawInput('ISBN ? ') isbn = rawInput('ISBN ? ')
elif filetype == 'article': elif filetype == 'article':
warning("Could not determine the DOI for "+src+", switching to manual " + warning("Could not determine the DOI for "+src +
"entry.") ", switching to manual entry.")
doi = rawInput('DOI ? ') doi = rawInput('DOI ? ')
elif filetype == 'book': elif filetype == 'book':
warning("Could not determine the ISBN for "+src+", switching to manual " + warning("Could not determine the ISBN for "+src +
"entry.") ", switching to manual entry.")
isbn = rawInput('ISBN ? ') isbn = rawInput('ISBN ? ')
elif doi is not False: elif doi is not False:
print("DOI for "+src+" is "+doi+".") print("DOI for "+src+" is "+doi+".")
@ -308,7 +309,8 @@ def delete_id(ident):
Delete a file based on its id in the bibtex file Delete a file based on its id in the bibtex file
""" """
with open(params.folder+'index.bib', 'r') as fh: with open(params.folder+'index.bib', 'r') as fh:
bibtex = BibTexParser(fh).get_entry_dict() bibtex = BibTexParser(fh, customization=homogeneize_latex_encoding)
bibtex = bibtex.get_entry_dict()
if ident not in bibtex.keys(): if ident not in bibtex.keys():
return False return False
@ -328,7 +330,8 @@ def delete_file(filename):
Delete a file based on its filename Delete a file based on its filename
""" """
with open(params.folder+'index.bib', 'r') as fh: with open(params.folder+'index.bib', 'r') as fh:
bibtex = BibTexParser(fh).get_entry_dict() bibtex = BibTexParser(fh, customization=homogeneize_latex_encoding)
bibtex = bibtex.get_entry_dict()
found = False found = False
for key in bibtex.keys(): for key in bibtex.keys():
@ -355,7 +358,8 @@ if __name__ == '__main__':
if sys.argv[1] == 'import': if sys.argv[1] == 'import':
if len(sys.argv) < 3: if len(sys.argv) < 3:
sys.exit("Usage : " + sys.argv[0] + " import FILE [article|book]") sys.exit("Usage : " + sys.argv[0] +
" import FILE [article|book]")
filetype = None filetype = None
if len(sys.argv) > 3 and sys.argv[3] in ["article", "book"]: if len(sys.argv) > 3 and sys.argv[3] in ["article", "book"]:

49
server.py Executable file
View File

@ -0,0 +1,49 @@
#!/usr/bin/env python2
# -*- coding: utf8 -*-
import os
import params
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from bibtexparser.bparser import BibTexParser
from bibtexparser.customization import homogeneize_latex_encoding
# TODO :
# * custom port
# * allow remote
def bibtex2HTML(data):
html = '<html><body>'
for index in data:
html += '<p>'+index+'</p>'
html += '</body></html>'
return html
PORT_NUMBER = 8080
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
if os.path.isfile(params.folder+'index.bib'):
with open(params.folder+"index.bib", "r") as fh:
bibtex = BibTexParser(fh, customization=homogeneize_latex_encoding)
bibtex = bibtex.get_entry_dict()
html = bibtex2HTML(bibtex)
else:
html = '<html><body><p>Not found.</p></body></html>'
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(html)
return
def log_message(self, format, *args):
return
if __name__ == '__main__':
try:
server = HTTPServer(('127.0.0.1', PORT_NUMBER), myHandler)
print('Webserver started : http://localhost:' + str(PORT_NUMBER))
server.serve_forever()
except KeyboardInterrupt:
print('KeyboardInterrupt received, shutting down the webserver…')
server.socket.close()