Exemplo n.º 1
1
def gen_bar_code(request, code):
    """Generate a bar code"""

    fp = StringIO()

    wr = barcode.writer.ImageWriter()
    wr.format = 'JPEG'

    barcode.generate('isbn' if isbnlib.is_isbn13(code) else 'code39', str(code), writer=wr, output=fp, writer_options={'write_text': False, 'module_width': 0.1, 'module_height': 2.0, 'quiet_zone': 0.0})

    return HttpResponse(fp.getvalue(), content_type="image/png")
Exemplo n.º 2
0
def getISBN(zibianma):
    isbntry = zibianma[:-4]
    if len(isbntry) == 10 and isbnlib.is_isbn10(isbntry):
        return isbntry
    elif len(isbntry) == 13 and isbnlib.is_isbn13(isbntry):
        return isbntry
    elif len(isbntry) == 11 and isbnlib.is_isbn10(isbntry[:-1]):
        return isbntry[:-1]
    elif len(isbntry) == 14 and isbnlib.is_isbn13(isbntry[:-1]):
        return isbntry[:-1]
    else:
        return None
    return None
Exemplo n.º 3
0
    def form_valid(self, form):
        self.publication = form.save(commit=False)
        self.publication.created_by = self.request.user
        works = Works()
        if self.publication.DOI != "" and works.doi_exists(self.publication.DOI):
            paper_data_result = works.doi(self.publication.DOI)
            self.publication.publication_year = str(paper_data_result.get('created').get('date-parts')[0][0])
            self.publication.title = paper_data_result.get('title')[0]
            self.publication.author = f"{paper_data_result.get('author')[0].get('given')},{paper_data_result.get('author')[0].get('family')}"
            sub = paper_data_result.get("subject", [self.publication.subject])
            self.publication.subject = ', '.join([str(elem) for elem in sub])
            self.publication.URL = paper_data_result.get('URL')

        elif self.publication.ISBN != "" and is_isbn13(self.publication.ISBN):
            book_data_result = meta(self.publication.ISBN)
            self.publication.publication_year = book_data_result.get('Year')
            self.publication.title = book_data_result.get('Title')
            self.publication.author = book_data_result.get('Authors')[0]

        elif self.publication.crossref and (self.publication.DOI or self.publication.ISBN):
            messages.error(self.request, 'DOI/ISBN no encontrado. Cargar datos y desmarcar el campo "tiene DOI/ISBN"')
            return render(self.request, 'bibliography/publication_form.html', {'form': form})
        self.publication.save()
        messages.success(self.request, "Registro realizado con exito")

        return redirect('bibliography:publication_detail', pk=self.publication.pk)
Exemplo n.º 4
0
def search(request):
    page = int(request.GET.get('p', '1'))
    if page < 1:
        page = 1

    query = request.POST.get('q', '')
    if query == '' and 'q' in request.GET:
        query = request.GET.get('q', '')

    if isbnlib.is_isbn10(query) or isbnlib.is_isbn13(query):
        try:
            book = Book.objects.filter(verified=True).get(Q(isbn10=query) | Q(isbn13=query))
            if request.user.is_authenticated:
                user = request.user
                bookshelf_set = Bookshelf.objects.filter(reader__user=user).filter(book=book)
                book.owned = bookshelf_set.count() == 1

            return render(request, 'books/detail.html', {'book': book})
        except Book.DoesNotExist:
            pass

    books = []
    total = 0

    if query != '':
        query_set = Book.objects.filter(
            Q(title__icontains=query)
            | Q(subtitle__icontains=query)
            | Q(authors__icontains=query)).filter(verified=True).order_by('-added_date')
        total = query_set.count()
        books = query_set[(10 * (page - 1)):10 * page]

    return render(request, 'books/search.html', {'q': query, 'books': books, 'total': total, 'page': page})
Exemplo n.º 5
0
	def isbn(self,isbn):
		#adds isbn to google spread sheet
		
		#check if valid
		clean_isbn = isbnlib.clean(isbn)
		if isbnlib.notisbn(clean_isbn):
			return "not valid isbn"
		
		#should check if has been collected before

		canonical = None;
		#first check trove
		canonical = self.trove.extract(clean_isbn);
		if not canonical :
			# try alternative isbn form
			print "trying alternative form "
			alt_isbn = clean_isbn;
			if isbnlib.is_isbn13(clean_isbn):
				alt_isbn = isbnlib.to_isbn10(clean_isbn)
			else :
				alt_isbn = isbnlib.to_isbn13(clean_isbn)
			canonical = self.trove.extract(alt_isbn);
			if canonical :
				clean_isbn = alt_isbn
		if not canonical :
			canonical = self.__reduce_metadata(clean_isbn,['merge','isbndb','openl'])
			if not canonical:
				return "no metadata found for isbn: " + clean_isbn
			canonical['source']='isbnlib'
			canonical["Authors"] = u', '.join(canonical["Authors"])
			canonical['link']=None

		row_data = ['isbn:'+clean_isbn, canonical["Title"], canonical["Authors"], canonical["Year"], canonical["Publisher"],canonical['link']]
		return self.__add_and_render(row_data)
Exemplo n.º 6
0
def isbn_lookup(isbnlike, good_reads):
    """
    Fetch in Good Reads for a given ISBN code
    """
    book_info = {}

    val = [c for c in isbnlike if c.isdigit()]
    isbn = ''.join(val)

    if isbnlib.is_isbn10(val):
        isbn = isbnlib.to_isbn13(val)

    if isbnlib.is_isbn13(isbn):
        try:
            book = good_reads.book(isbn=isbn)

            publisher = book.publisher if book.publisher is not None else '-'
            pages_qty = book.num_pages if book.num_pages is not None else int(
                0)

            book_info.update({
                'Título': book.title,
                'Autor': str(book.authors[0]),
                'Editora': publisher,
                'ISBN-13': isbn,
                'Qtd. de Páginas': pages_qty,
                'Link': book.link
            })
        except Exception as e:
            logger.exception('{}'.format(e), exc_info=False)
        finally:
            return book_info
    else:
        return book_info
Exemplo n.º 7
0
def isISBN(input_str):
    ''' Checks if the given string is an ISBN number. '''

    if isbnlib.is_isbn10(input_str):
        return True
    if isbnlib.is_isbn13(input_str):
        return True

    input_str_clean = isbnlib.clean(input_str)

    if isbnlib.is_isbn10(input_str_clean):
        return True
    if isbnlib.is_isbn13(input_str_clean):
        return True

    return False
Exemplo n.º 8
0
Arquivo: pdf.py Projeto: niwyss/Book
	def extractISBN(self):

		isbn = None;

		rsrcmgr = PDFResourceManager()
		retstr = StringIO()
		device = TextConverter(rsrcmgr, retstr, codec='utf-8', laparams=LAParams())
		interpreter = PDFPageInterpreter(rsrcmgr, device)

		for page in PDFPage.get_pages(self.pdf, set(), maxpages=0, password="",caching=True, check_extractable=True):

			# Get the text from the page
			interpreter.process_page(page)
			text = retstr.getvalue()
			retstr.truncate(0)

			# Extract ISBN
			isbn = self.searchCodeInPage(text)

			if isbn:
				break

		device.close()
		retstr.close()

		# Convert to ISBN 10 and 13
		if isbnlib.is_isbn10(isbn):
			self.isbn10 = isbn
			self.isbn13 = isbnlib.to_isbn13(self.isbn10)
		elif isbnlib.is_isbn13(isbn):
			self.isbn13 = isbn
			self.isbn10 = isbnlib.to_isbn10(self.isbn13)
Exemplo n.º 9
0
async def load(ctx, path: str = 'books.csv'):
    """Load books from a CSV file on disk.

	Args:
		ctx: Discord message content
		path: Path of file to load books from.
	"""
    if await auth_check(ctx) and await channel_check(ctx):
        with open(path) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            line_count = 0
            for row in csv_reader:
                if line_count == 0:
                    line_count += 1
                else:
                    row = [None if x == '' else x for x in row
                           ]  # Convert empty values into None types
                    isbn = row[5]
                    if isbnlib.is_isbn13(isbn):
                        try:
                            cursor.execute(
                                """
													INSERT INTO books ('title', 'binding', 'authors', 'series', 'available', 'isbn', 'location')
													VALUES (?, ?, ? ,? ,? ,?, ?)""", row[:-1])
                            line_count += 1
                        except sqlite3.IntegrityError:
                            await respond(ctx, ['Duplicate book found.'],
                                          admin=True)
                    else:
                        await respond(ctx, ['Invalid ISBN.'], admin=True)
        db.commit()
        await respond(
            ctx,
            ['Load complete.', 'Loaded ' + str(line_count - 1) + ' books.'],
            admin=True)
Exemplo n.º 10
0
 def type_and_identifier_for_urn(cls, identifier_string):
     if not identifier_string:
         return None, None
     m = cls.GUTENBERG_URN_SCHEME_RE.match(identifier_string)
     if m:
         type = Identifier.GUTENBERG_ID
         identifier_string = m.groups()[0]
     elif identifier_string.startswith("http:") or identifier_string.startswith("https:"):
         type = Identifier.URI
     elif identifier_string.startswith(Identifier.URN_SCHEME_PREFIX):
         identifier_string = identifier_string[len(Identifier.URN_SCHEME_PREFIX):]
         type, identifier_string = map(
             urllib.unquote, identifier_string.split("/", 1))
     elif identifier_string.startswith(Identifier.ISBN_URN_SCHEME_PREFIX):
         type = Identifier.ISBN
         identifier_string = identifier_string[len(Identifier.ISBN_URN_SCHEME_PREFIX):]
         identifier_string = urllib.unquote(identifier_string)
         # Make sure this is a valid ISBN, and convert it to an ISBN-13.
         if not (isbnlib.is_isbn10(identifier_string) or
                 isbnlib.is_isbn13(identifier_string)):
             raise ValueError("%s is not a valid ISBN." % identifier_string)
         if isbnlib.is_isbn10(identifier_string):
             identifier_string = isbnlib.to_isbn13(identifier_string)
     elif identifier_string.startswith(Identifier.OTHER_URN_SCHEME_PREFIX):
         type = Identifier.URI
     else:
         raise ValueError(
             "Could not turn %s into a recognized identifier." %
             identifier_string)
     return (type, identifier_string)
Exemplo n.º 11
0
def add_book(data):
    # add book to openlibrary.org

    # Define a Book Object
    authors = [
        common.Author(name=author) for author in data['authors'].split(', ')
    ]
    book = common.Book(
        title=data['title'],
        authors=authors,
        publisher=data['publisher'],
        publish_date=data['year'],
        pages=data['pages'],
    )

    # Add metadata like ISBN 10 and ISBN 13
    isbn = data['isbn']
    if is_isbn10(isbn):
        book.add_id('isbn_10', isbn)
    elif is_isbn13(isbn):
        book.add_id('isbn_13', isbn)

    # Create a new book
    ol = OpenLibrary()
    new_book = ol.create_book(book)

    new_book.add_bookcover(data['cover'])
    new_book.work.add_subject(data['categories'])
    new_book.save()

    return new_book
Exemplo n.º 12
0
    async def check(self, entry):
        length = self._cfg.get('isbn_length', entry, 13)
        if not length:
            return []

        isbn = entry.data.get('isbn')
        if not isbn:
            return []

        clean_isbn = clean(isbn)
        if not clean_isbn or notisbn(clean_isbn):
            return []

        if length not in (10, 13):
            raise ConfigurationError(
                "The option 'isbn_length' must be either of 10 or 13.")

        if length == 10:
            if not is_isbn10(clean_isbn):
                return [(type(self).NAME,
                         "ISBN '{}' is not of length 10.".format(isbn),
                         "ISBN-10 would be '{}'".format(to_isbn10(clean_isbn)))
                        ]
        elif length == 13:
            if not is_isbn13(clean_isbn):
                return [(type(self).NAME,
                         "ISBN '{}' is not of length 13.".format(isbn),
                         "ISBN-13 would be '{}'".format(to_isbn13(clean_isbn)))
                        ]

        return []
Exemplo n.º 13
0
def search_add(isbn):
    db = sqlite3.connect('test.db')
    db.row_factory = sqlite3.Row
    cursor = db.cursor()

    if isbnlib.is_isbn13(isbn):
        info = isbnlib.meta(isbn)
        au = ", ".join(info['Authors'])
        addBook(cursor, info['ISBN-13'], info['Title'], au, info['Year'],
                info['Publisher'], getCoverSmall(isbn), getCover(isbn),
                getDesc(isbn))

        db.commit()
        return search_equals(cursor, 'ISBN', isbn)
    elif isbnlib.is_isbn10(isbn):
        isbn = isbnlib.to_isbn13(isbn)
        info = isbnlib.meta(isbn)
        au = ", ".join(info['Authors'])
        addBook(cursor, info['ISBN-13'], info['Title'], au, info['Year'],
                info['Publisher'], getCoverSmall(isbn), getCover(isbn),
                getDesc(isbn))

        db.commit()
        return search_equals(cursor, 'ISBN', isbn)
    else:
        print("Not a valid ISBN")
        return None

    db.commit()
    db.close()
Exemplo n.º 14
0
def check_tweet(tweet, parent=False):
    if parent:
        print("In parent")
        print(tweet.full_text)
        print(tweet.in_reply_to_status_id)
        if tweet.in_reply_to_status_id:
            tweet = api.get_status(tweet.in_reply_to_status_id, tweet_mode="extended")
            print(tweet.full_text)
        else:
            return []
    
    text = tweet.full_text
    words = text.split()
    isbnlike = isbnlib.get_isbnlike(text, level='normal')

    print(isbnlike)
    print(words)

    for word in words:
        if word.startswith("http") or word.startswith("https"):
            print(word)
            resp = requests.head(word)
            print(resp.headers["Location"])
            if "amazon" in resp.headers["Location"] and "/dp/" in resp.headers["Location"]:
                amazon_text = isbnlib.get_isbnlike(
                    resp.headers["Location"], level='normal')
                amazon_text = list(dict.fromkeys(amazon_text))
                for item in amazon_text:
                    if isbnlib.is_isbn10(item) or isbnlib.is_isbn13(item):
                        isbnlike.append(item)

    print(isbnlike)

    return isbnlike
Exemplo n.º 15
0
def check_isbn(form, field):
    field.data = field.data.replace("-", "").replace(" ", "")
    if not is_isbn10(field.data) and not is_isbn13(field.data):
        raise ValidationError("ISBN number is incorrect!")

    if Book.query.filter_by(isbn=field.data).first():
        raise ValidationError("This book is already in the database.")
Exemplo n.º 16
0
 def type_and_identifier_for_urn(cls, identifier_string):
     if not identifier_string:
         return None, None
     m = cls.GUTENBERG_URN_SCHEME_RE.match(identifier_string)
     if m:
         type = Identifier.GUTENBERG_ID
         identifier_string = m.groups()[0]
     elif identifier_string.startswith(
             "http:") or identifier_string.startswith("https:"):
         type = Identifier.URI
     elif identifier_string.startswith(Identifier.URN_SCHEME_PREFIX):
         identifier_string = identifier_string[len(Identifier.
                                                   URN_SCHEME_PREFIX):]
         type, identifier_string = map(urllib.unquote,
                                       identifier_string.split("/", 1))
     elif identifier_string.startswith(Identifier.ISBN_URN_SCHEME_PREFIX):
         type = Identifier.ISBN
         identifier_string = identifier_string[len(Identifier.
                                                   ISBN_URN_SCHEME_PREFIX):]
         identifier_string = urllib.unquote(identifier_string)
         # Make sure this is a valid ISBN, and convert it to an ISBN-13.
         if not (isbnlib.is_isbn10(identifier_string)
                 or isbnlib.is_isbn13(identifier_string)):
             raise ValueError("%s is not a valid ISBN." % identifier_string)
         if isbnlib.is_isbn10(identifier_string):
             identifier_string = isbnlib.to_isbn13(identifier_string)
     elif identifier_string.startswith(Identifier.OTHER_URN_SCHEME_PREFIX):
         type = Identifier.URI
     else:
         raise ValueError(
             "Could not turn %s into a recognized identifier." %
             identifier_string)
     return (type, identifier_string)
Exemplo n.º 17
0
    def post(self, request, *args, **kwargs):
        action = request.POST['create']
        new_order = request.session['new_order']
        transactions = request.session['transactions']
        grand_total = request.session['grand_total']
        grand_total_paid = request.session['grand_total_paid']

        form_class = self.get_form_class()
        form = self.get_form(form_class)
        context = {'form': form}

        if action == 'Add':
            isbn_maybe = request.POST['ISBN']
            quantity = request.POST['Quantity']

            if is_isbn10(isbn_maybe) or is_isbn13(isbn_maybe):
                isbn_raw = canonical(isbn_maybe)
                books = get_tradeable_books(isbn_raw)
                if len(books) == 0:
                    context['error'] = 'Do not buy'
                else:
                    book = books[0].as_book()
                    transaction = Transaction(
                        book=book,
                        subtotal=transaction_subtotal(new_order, books[0],
                                                      quantity),
                        subtotal_paid=transaction_subtotal_paid(
                            new_order, books[0], quantity),
                        quantity=quantity,
                        notes='')
                    transactions.append(transaction)
                    grand_total += transaction.subtotal
                    grand_total_paid += transaction.subtotal_paid
                    request.session['transactions'] = transactions
                    request.session['grand_total'] = grand_total
                    request.session['grand_total_paid'] = grand_total_paid
            else:
                # isbn check failed
                context['error'] = 'Not ISBN'
        elif action == 'Submit':
            if transactions == []:
                context['error'] = 'You need to add at least one book.'
            else:
                return redirect('orders:confirm')
        elif action == 'Cancel':
            transactions = []
            grand_total = Decimal(0).quantize(Decimal('0.01'),
                                              rounding=ROUND_DOWN)
            grand_total_paid = Decimal(0).quantize(Decimal('0.01'),
                                                   rounding=ROUND_DOWN)
            request.session['transactions'] = transactions
            request.session['grand_total'] = grand_total
            request.session['grand_total_paid'] = grand_total_paid
            # context['error'] = 'Cancel order'
        context['new_order'] = request.session['new_order']
        context['transactions'] = request.session['transactions']
        context['grand_total'] = request.session['grand_total']
        context['grand_total_paid'] = request.session['grand_total_paid']
        return render(request, self.template_name, context)
Exemplo n.º 18
0
    def clean_isbn(self):
        cleaned_data = self.cleaned_data
        isbn = cleaned_data.get("isbn")

        if isbnlib.is_isbn10(isbn) or isbnlib.is_isbn13(isbn):
            return cleaned_data
        else:
            raise forms.ValidationError("This is not a valid isbn number.")
Exemplo n.º 19
0
def mangle_isbn(raw):
    result = dict()
    for value in raw.strip().split():
        if isbnlib.is_isbn13(value):
            result['isbn13'] = isbnlib.mask(value)
        elif isbnlib.is_isbn10(value):
            result['isbn10'] = isbnlib.mask(value)
    return result
Exemplo n.º 20
0
def get_title(isbn_numbers):

    for isbn in isbn_numbers:
        cleaned_isbn = isbnlib.clean(isbn)
        if (isbnlib.is_isbn13(cleaned_isbn)
                or isbnlib.is_isbn10(cleaned_isbn)):
            book = isbnlib.meta(cleaned_isbn)
            return book['Title']
            break
Exemplo n.º 21
0
def newbook():
    if request.method == 'POST':
        barcode = str(request.form['barcode'])
        isbn = isbnlib.canonical(request.form['isbn'])
        # invoice = request.form['invoice']
        error = None
        author = None
        lang = None
        publisher = None
        title = None
        publYear = None
        db = get_db()

        # Ensure barcode has not already been inserted to Database
        if db.execute('SELECT id FROM new_book WHERE barcode = ?',
                      (barcode, )).fetchone() is not None:
            error = 'Barcode {} is already captured.'.format(barcode)

        # Checks correct barcode length
        elif int(len(barcode)) != 24:
            error = '{} is an incorrect length.'.format(barcode)

        # ISBN Validation
        elif isbnlib.is_isbn10(isbn) is not True:
            if isbnlib.is_isbn13(isbn) is not True:
                error = f'{isbn} is not a valid ISBN'

        if error is not None:
            flash(error)
        else:
            try:
                book_lib = (isbnlib.meta(isbn, service='goob',
                                         cache='default'))
                # Display meta data to user.
                flash(book_lib)

                # Assign meta dictionary values to variables for insertion to DB.
                author = str(book_lib['Authors'])
                lang = book_lib['Language']
                publisher = book_lib['Publisher']
                title = book_lib['Title']
                publYear = book_lib['Year']

            # Catch exception error for book that was not found on search.
            except NoDataForSelectorError:
                flash("Book recorded: Author, Title not found.")
                pass
            # execute query and insert data
            db.execute(
                'INSERT INTO new_book (barcode, isbn, author_id, author, lang, publisher, title, publYear)'
                ' VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                (barcode, isbn, g.user['id'], author, lang, publisher, title,
                 publYear))
            db.commit()
            return redirect(url_for('book.newbook'))

    return render_template('book/newbook.html')
Exemplo n.º 22
0
def fix_isbn(entry):
    if 'isbn' in entry:
        value = entry['isbn']
        if isbnlib.is_isbn10(value):
            value = isbnlib.to_isbn13(value)
        if not isbnlib.is_isbn13(value):
            raise Exception(f'invalid isbn in {entry["ID"]}: {entry["isbn"]}')
        entry['isbn'] = isbnlib.mask(value, separator='-')
    return entry
def check_valid_isbn(x):
    """Check if it is a ISBN. Returns the isbn if it is valid. None otherwise.
    """
    for i in range(len(x)):
        if isbnlib.is_isbn10(x[i:i+10]):
            return x[i:i+10]
        elif isbnlib.is_isbn13(x[i:i+13]):
            return x[i:i+13]
    return None
Exemplo n.º 24
0
    def clean(self):
        data = self.cleaned_data

        isbn = data.get('isbn')
        if i.get_isbnlike(isbn):
            if i.is_isbn10(isbn) or i.is_isbn13(isbn):
                return True
            raise ValidationError(
                'ISBN does not seem to be a ISBN13 or ISBN10')
        raise ValidationError('ISBN does not seem valid')
Exemplo n.º 25
0
def RandomBookLookup():
    while True:
        randomID = random.randint(1000000000000, 9999999999999)
        randomID = str(randomID)
        if isbnlib.is_isbn13(randomID):
            print("Book found! {}".format(randomID))
            webbrowser.open("https://isbnsearch.org/isbn/{}".format(randomID))
            return
        else:
            print("Not no book found. Looping. {}".format(randomID))
Exemplo n.º 26
0
def randomBook_lookup():
    while True:
        random_id = random.randint(1000000000000, 9999999999999)
        random_id = str(random_id)
        if isbnlib.is_isbn13(random_id):
            print("Book found! {}".format(random_id))
            webbrowser.open(f"https://isbnsearch.org/isbn/{random_id}")
            return
        else:
            print(f"No book found on ISBN13 {random_id}. Looping.")
Exemplo n.º 27
0
def propose(request):

    error = False

    sections = Section.objects.order_by('pk').all()
    semestres = Semester.objects.order_by('pk').all()

    isbn = ''
    annotated = False
    highlighted = ''
    state = ''
    comment = ''
    price = 0

    if request.method == 'POST':

        isbn = clean_isbn(request.POST.get('isbn', ''))
        if not isbnlib.is_isbn13(isbn):
            isbn = ''

        annotated = request.POST.get('annotated', '') == 'annotated'
        highlighted = request.POST.get('highlighted', '') == 'highlighted'
        state = request.POST.get('state', '')

        if state not in ['neuf', 'bon', 'acceptable', 'mauvais']:
            state = ''

        comment = request.POST.get('comment')
        try:
            price = int(request.POST.get('price'))
        except:
            price = 0

        if isbn == '' or state == '' or price <= 0 or request.POST.get('terms') != 'terms':
            error = True
        else:

            c = Candidate(isbn=isbn, sciper=request.user.get_sciper(), annotated=annotated, highlighted=highlighted, state=state, comments=comment, price=price)
            c.save()

            for sec in sections:
                for sem in semestres:
                    if request.POST.get('c_%s_%s' % (sec.pk, sem.pk, )):
                        CandidateUsage(candidate=c, section=sec, semester=sem).save()
            return render(request, 'polybookexchange/propose_ok.html', {'c': c})

    checks_to_check = []

    for sec in sections:
        for sem in semestres:
            key = 'c_' + str(sec.pk) + '_' + str(sem.pk)
            if request.POST.get(key):
                checks_to_check.append(key)

    return render(request, 'polybookexchange/propose.html', {'error': error, 'sections': sections, 'semestres': semestres, 'isbn': isbn, 'annotated': annotated, 'highlighted': highlighted, 'price': price, 'comment': comment, 'checks_to_check': checks_to_check})
Exemplo n.º 28
0
def get_isbn_info(isbn):
    if isbn.lower().startswith('isbn:'):
        isbn = isbn[5:]
    is_isbn = is_isbn10(isbn) or is_isbn13(isbn)
    if not is_isbn:
        raise ValidationError(isbn='Not a valid ISBN.')
    match = spreads.metadata.get_isbn_metadata(isbn)
    if match:
        return jsonify(match)
    else:
        raise ValidationError(isbn='Could not find match for ISBN.')
Exemplo n.º 29
0
 def isbn(self, value):
     if not value:
         self._isbn = ''
     else:
         try:
             if isbnlib.is_isbn13(value):
                 self._isbn = isbnlib.canonical(value)
             elif isbnlib.is_isbn10(value):
                 self._isbn = isbnlib.to_isbn13(value)
         except:
             raise ValueError('Invalid ISBN {}'.format(value))
Exemplo n.º 30
0
def extract_identifiers_from_row(row, isbn_columns):
    cols = [int(x) for x in isbn_columns.split(',')]
    isbns = set()
    for isbn_column in cols:
        raw = row[isbn_column].strip('"=')
        isbns.add(raw)
        # Transform to ISBN 10 or 13.
        if isbnlib.is_isbn13(raw):
            isbns.add(isbnlib.to_isbn10(raw))
        elif isbnlib.is_isbn10(raw):
            isbns.add(isbnlib.to_isbn13(raw))
    return isbns
Exemplo n.º 31
0
def add_book():
    form = AddBookForm()
    if form.validate_on_submit():
        isbn = request.form['isbn']
        if isbnlib.is_isbn13(isbn):
            isbn = isbnlib.to_isbn10(isbn)
        if not isbnlib.is_isbn10(isbn):
            flash('Enter valid ISBN', 'error')
            return redirect(url_for('admin_page.add_book'))

        book_data = isbnlib.meta(isbn)
        book_cover = isbnlib.cover(isbn)
Exemplo n.º 32
0
def isbn_to_asin(isbn):  # returns isbn10 (asin)
    clean = isbnlib.canonical(isbn)
    if (len(isbn) == 10):
        if (isbnlib.is_isbn10(clean)):
            return clean
        else:
            return '0'
    elif (len(isbn) == 13):
        if (isbnlib.is_isbn13(clean)):
            return isbnlib.to_isbn10(clean)
    else:
        return '0'
Exemplo n.º 33
0
def addISBNFromUser(filename):
    # Get input from user
    UserISBN = input("Please enter ISBN (including '-'): ")
    # Check its legit
    if isbnlib.is_isbn13(UserISBN) == True or isbnlib.is_isbn10(
            UserISBN) == True:
        # Add book based on ISBN
        print("Saving data...")
        addBookToISBNLibrary(filename, UserISBN)
        print("Done!")
    else:
        print("Invalid ISBN")
Exemplo n.º 34
0
def is_isbn_code(search):
    """checks if the received string is valid isbn number"""
    check = ''.join(ch for ch in search if ch.isalnum())

    if is_isbn13(check):
        return to_isbn10(check)

    if is_isbn10(check):
        return check

    else:
        return False
Exemplo n.º 35
0
def lookup_ISBN(book_isbn):
    if isbnlib.is_isbn13(book_isbn):
        trimmed_id = isbnlib.canonical(book_isbn)
        webbrowser.open(f"https://isbnsearch.org/isbn/{trimmed_id}")
    else:
        if isbnlib.is_isbn10(book_isbn):
            trimmed_id_isbn10 = isbnlib.canonical(book_isbn)
            webbrowser.open(f"https://isbnsearch.org/isbn/{trimmed_id_isbn10}")
        else:
            print(
                "Invalid input. Please check to see if it is in either ISBN13 or ISBN10."
            )
Exemplo n.º 36
0
def clean_isbn(isbn):
    """
    Checks if ISBN is valid and converts it to ISBN13 format without dashes
    """
    if isbnlib.is_isbn10(isbn):
        return isbnlib.to_isbn13(isbn)
    elif isbnlib.is_isbn13(isbn):
        return isbnlib.canonical(isbn)
    # test if wrongly prefixed isbn10
    if isbn.startswith("978"):
        return clean_isbn(isbn[3:])
    return ""
Exemplo n.º 37
0
def isbn_validator(isbnlike):
    """
    This is a validator for our isbn data. The Book class only accepts isbn13 format, so
    if this function receive a isbn10 it will raise a exception.
    """
    if (not is_isbn13(isbnlike)) or notisbn(isbnlike):
        raise ValidationError("ISBN invalid")
    else:
        try:
            m = meta(canonical(isbnlike))
            print(m)
        except Exception:
            raise ValidationError("ISBN valid but not used")
Exemplo n.º 38
0
def check_isbn(request):

    isbn = clean_isbn(request.GET.get('isbn', ''))

    if not isbnlib.is_isbn13(isbn):
        return HttpResponse('<script type="text/javascript">$(\'#form-group-isbn\').attr(\'class\', \'has-warning\');</script><span class="text-warning"><i class="glyphicon glyphicon-warning-sign"></i> %s</span>' % (unicode(_('Not an ISBN')), ))

    data = isbnlib.meta(str(isbn))

    if not data or not data.get('Authors'):
        return HttpResponse('<script type="text/javascript">$(\'#form-group-isbn\').attr(\'class\', \'has-danger\');</script><span class="text-danger"><i class="glyphicon glyphicon-remove"></i> %s</span>' % (unicode(_('Cannot found this ISBN in online databases')), ))

    return HttpResponse('<script type="text/javascript">$(\'#form-group-isbn\').attr(\'class\', \'has-success\');</script><span class="text-success"><i class="glyphicon glyphicon-ok"></i> %s</span>' % (unicode(_('Good ISBN !')), ))
Exemplo n.º 39
0
 def from_asin(cls, _db, asin, autocreate=True):
     """Turn an ASIN-like string into an Identifier.
     If the string is an ISBN10 or ISBN13, the Identifier will be
     of type ISBN and the value will be the equivalent ISBN13.
     Otherwise the Identifier will be of type ASIN and the value will
     be the value of `asin`.
     """
     asin = asin.strip().replace("-", "")
     if isbnlib.is_isbn10(asin):
         asin = isbnlib.to_isbn13(asin)
     if isbnlib.is_isbn13(asin):
         type = cls.ISBN
     else:
         type = cls.ASIN
     return cls.for_foreign_id(_db, type, asin, autocreate)
Exemplo n.º 40
0
def get_isbn_info(isbn):
    if isbn.lower().startswith('isbn:'):
        isbn = isbn[5:]
    is_isbn = is_isbn10(isbn) or is_isbn13(isbn)
    if not is_isbn:
        errors = {'isbn': 'Not a valid ISBN.'}
        return make_response(json.dumps(dict(errors=errors)), 400,
                             {'Content-Type': 'application/json'})
    match = spreads.metadata.get_isbn_metadata(isbn)
    if match is None:
        return make_response(
            json.dumps({'errors': {'isbn': 'Could not find match for ISBN.'}}),
            404, {'Content-Type': 'application/json'})
    else:
        return jsonify(match)
Exemplo n.º 41
0
def get_isbn_info(isbn):
    """ Get metadata for a given ISBN number.

    :param isbn:    ISBN number to retrieve metadata for
    :type isbn:     str/unicode with valid ISBN-10 or ISBN-13, optionally
                    prefixed with `isbn:`

    :resheader Content-Type: :mimetype:`application/json`
    :status 200:    When the ISBN was valid and a match was found.
    :status 400:    When the ISBN was invalid or no match was found.
    """
    if isbn.lower().startswith('isbn:'):
        isbn = isbn[5:]
    is_isbn = is_isbn10(isbn) or is_isbn13(isbn)
    if not is_isbn:
        raise ValidationError(isbn='Not a valid ISBN.')
    match = spreads.metadata.get_isbn_metadata(isbn)
    if match:
        return jsonify(match)
    else:
        raise ValidationError(isbn='Could not find match for ISBN.')
Exemplo n.º 42
0
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_OAUTH, scope)
gc = gspread.authorize(credentials)
link = GOOGLE_SPREADSHEET
trove = Trove()
wks = gc.open_by_url(link).sheet1

for i in xrange(631,1000) :
	row = wks.row_values(i);
	if row[5] == 'None':
		isbn = row[0][5:]
		old_isbn = isbn;
		print 'getting ', isbn

		if isbnlib.is_isbn13(isbn):
			isbn = isbnlib.to_isbn10(isbn)
		else : 
			isbn = isbnlib.to_isbn13(isbn)
		canonical = trove.extract(isbn)
		if not canonical:
			canonical = trove.extract(old_isbn)
		if canonical :
			print '---------------------------'
			print 'Replacing', i, 'row'
			#print row
			row_data = ['isbn:'+isbn, canonical["Title"], canonical["Authors"], canonical["Year"], canonical["Publisher"],canonical['link']]
			#print row_data
			print "updating "
			for j in range(0,len(row_data)):
				print '-cell',i,j,':'
Exemplo n.º 43
0
def get_default_isbn(isbn_list):
    for isbn in isbn_list:
        if isbnlib.is_isbn13(isbn) or isbnlib.is_isbn10(isbn):
            return isbnlib.mask(isbn)

    return ""
Exemplo n.º 44
0
def add_book(request):

    candidate = None
    candidate_id = request.GET.get('candidate_id')

    if candidate_id:
        try:
            candidate = Candidate.objects.get(pk=request.GET.get('candidate_id'))
        except Candidate.DoesNotExist:
            pass

    isbn = request.GET.get('isbn')
    sciper = request.GET.get('sciper')

    if (isbn and isbnlib.is_isbn13(isbn) and sciper) or candidate:
        # Les paramètres de base on été envoyé (Candidat ou ISBN), on peut donc checker si le livre existe

        bonusC = '&candidate_id=%s' % (candidate.pk, ) if candidate else ''

        if candidate:
            isbn = candidate.isbn
            sciper = candidate.sciper
        else:
            sciper = int(sciper)

        if request.method == 'POST':
            # Le formulaire de création d'un livre à été envoyé

            book = get_object_or_404(Book, isbn=isbn)  # Has been created before
            book.title = request.POST.get('title')
            book.year = request.POST.get('year')
            book.edition = request.POST.get('edition')

            book.save()

            book.publisher, _ = Publisher.objects.get_or_create(name=request.POST.get('publisher', 'Unknow').strip())
            book.author.clear()

            for author in request.POST.get('authors', '').split(','):
                author = author.strip()

                if author:
                    author_object, _ = Author.objects.get_or_create(name=author)
                    book.author.add(author_object)

            book.update_cover()

        # On regarde ce qu'on est censé faire
        try:
            # If the book exist, let's add the exemplar
            book = Book.objects.get(isbn=isbn)
            return HttpResponseRedirect(reverse('polybookexchange.views.add_exemplar') + '?isbn=%s&sciper=%s%s' % (isbn, sciper, bonusC,))
        except Book.DoesNotExist:
            # Display the form
            book = Book(edition='1', isbn=isbn)
            book.update_metadata()

            return render(request, 'polybookexchange/add_book_new_book.html', {'book': book})

    else:
        # Aucun paramètre passé. On demande l'isbn et le sciper
        return render(request, 'polybookexchange/add_book_request.html', {'warning_candidate': candidate_id and not candidate})
Exemplo n.º 45
0
def add_exemplar(request):

    candidate = None
    candidate_id = request.GET.get('candidate_id')

    if candidate_id:
        try:
            candidate = Candidate.objects.get(pk=request.GET.get('candidate_id'))
        except Candidate.DoesNotExist:
            pass

    isbn = clean_isbn(request.GET.get('isbn'))
    sciper = request.GET.get('sciper')

    sections = Section.objects.order_by('pk').all()
    semestres = Semester.objects.order_by('pk').all()

    if request.GET.get('candidate_id', '') != '':
        try:
            candidate = Candidate.objects.get(pk=request.GET.get('candidate_id'))
        except:
            pass

    if isbn and sciper and isbnlib.is_isbn13(isbn) or candidate:

        if candidate:
            isbn = candidate.isbn
            sciper = candidate.sciper
        else:
            sciper = int(request.GET.get('sciper'))

        book = Book.objects.get(isbn=isbn)

        if request.method == 'POST':
            annotated = request.POST.get('annotated') == 'annotated'
            highlighted = request.POST.get('highlighted') == 'highlighted'
            state = request.POST.get('state')
            comment = request.POST.get('comment')
            price = request.POST.get('price')

            e = Exemplar(book=book, price=price, seller_id=sciper, annotated=annotated, highlighted=highlighted, state=state, comments=comment)
            e.save()

            book.qty_in_stock += 1
            book.avg_price = Exemplar.objects.filter(book=book).aggregate(Avg('price'))['price__avg']
            book.save()

            for sec in sections:
                for sem in semestres:
                    if request.POST.get('c_' + str(sec.pk) + '_' + str(sem.pk)):
                        UsedBy.objects.get_or_create(book=book, section=sec, semester=sem)

            send_templated_mail(_('AGEPoly\'s book exchange: Exemplar in sale'), settings.POLYBOOKEXCHANGE_EMAIL_FROM, [sciper2mail(e.seller_id)], 'book_insale', {'exemplar': e})

            if candidate:
                candidate.delete()

            return redirect('polybookexchange.views.exemplar', e.pk)

        else:
            return render(request, 'polybookexchange/add_exemplar.html', {'book': book, 'sciper': sciper, 'candidate': candidate, 'sections': sections, 'semestres': semestres})
Exemplo n.º 46
0
Arquivo: models.py Projeto: DSIW/sdf
def validate_isbn13(value):
      if not isbnlib.is_isbn13(value):
          raise ValidationError('%s ist keine ISBN-13 Nummer' % value)
Exemplo n.º 47
0
 def check_isbn(self, path, el):
     if not isbnlib.is_isbn13(el.text) and not isbnlib.is_isbn10(el.text):
         msg = 'Invalid ISBN: %s' % el.text
         self.add_message(msg, path, el)
Exemplo n.º 48
0
isbns = {}

rows = csv.reader(sys.stdin, delimiter=',')
for row in rows:
    if len(row) != 2:
        continue
    [ title, isbn ] = row

    if isbn is None:
        continue
    if len(isbn) == 10:
        isbn = isbntools.app.to_isbn13(isbn)
        if isbn is None:
            continue
    if len(isbn) != 13:
        continue
    if not isbnlib.is_isbn13(isbn):
        print("skipping invalid isbn of", isbn, "from article", title, file=sys.stderr)
        continue

    isbns[isbn] = isbns.get(isbn,0) + 1

sorted_list = ((i, isbns[i]) for i in sorted(isbns, key=isbns.get, reverse=True))

for i, count in sorted_list:
    print(count, i)



def process(ia_id, entry):
    if entry == '': # first entry will be empty
        return

    meta = {}

    # the entry may or may not have carriage returns. don't depend on them.

    matches = re.findall('dc:title\>([^\<]+)\</dc:title', entry)
    if len(matches) > 1:
        print("multiple dc:title seen in", ia_id)
        return
    elif len(matches) == 1:
        meta['title'] = matches[0].rstrip(',.').strip()

    matches = re.findall('dc:publisher\>([^\<]+)\</dc:publisher', entry)
    if len(matches) > 1:
        print("multiple dc:publisher seen in", ia_id)
        return
    elif len(matches) == 1:
        publisher = matches[0].rstrip(',.').strip().replace('\n', ' ').replace('  ', ' ')
        meta['publisher'] = publisher

    matches = re.findall('dc:date\>([^\<]+)\</dc:date', entry)
    if len(matches) > 1:
        print("multiple dc:date seen in", ia_id)
        return
    elif len(matches) == 1:
        meta['date'] = matches[0].rstrip(',.').strip()

    isbn_seen = {}

    matches = re.findall('dc:identifier\>([^\<]+)\</dc:identifier', entry)
    for m in matches:
        if m.startswith('URN:ISBN:'):
            m = m[len('URN:ISBN:'):] # strip off that prefix
            m = m.rstrip('.,')
            # m = m.replace(' ','') -- doesn't fit with the excuse syntax?
            m = m.replace('\n',' ') # sometimes between isbn and excuse
            m = m.replace('-','')
            excuse = ''
            if ' ' in m:
                isbn, excuse = m.split(' ', maxsplit=1)
            else:
                isbn = m
            if len(isbn) == 10:
                isbn = isbntools.app.to_isbn13(isbn)
                if isbn is None: # failed conversion
                    print("failed conversion of isbn10 to isbn13 in", ia_id)
                    continue
            if len(isbn) != 13:
                print("bad length of isbn", isbn, "in", ia_id)
                continue
            if not isbnlib.is_isbn13(isbn):
                print("invalid isbn13 of", isbn, "in", ia_id)
                continue

            if isbn in isbn_seen:
                if excuse != '':
                    meta['isbn13s'][isbn] = excuse
            else:
                meta['isbn13s'] = meta.get('isbn13s', {})
                meta['isbn13s'][isbn] = excuse

                isbn13_to_ia_id[isbn] = isbn13_to_ia_id.get(isbn, [])
                isbn13_to_ia_id[isbn].append(ia_id) # ok because writeback=True

                isbn_seen[isbn] = 1
        else:
            if m.startswith('http'):
                continue
            print("found a non-ISBN identifier in", ia_id, "of", m)

    metadata[ia_id] = meta
    return
Exemplo n.º 50
0
 def check_value(self, value):
     return is_isbn10(value) or is_isbn13(value)
Exemplo n.º 51
0
 def process_identifier(self, identifier):
     isbn = identifier.identifier
     if isbn and (isbnlib.is_isbn10(isbn) or isbnlib.is_isbn13(isbn)):
         self.client.measure_popularity(identifier, self.client.ONE_YEAR_AGO)
     return True
def com_isbn_13_check(isbn_string):
    return isbnlib.is_isbn13(isbn_string)
Exemplo n.º 53
0
def verify_isbn():
    isbn = request.vars.isbn.strip()
    return isbnlib.is_isbn10(isbn) or isbnlib.is_isbn13(isbn)