<commit_before>#!/usr/bin/env python
import os
import urllib2
import json
import argparse

from pymongo import Connection


def get_books(api_host='localhost', api_port='5984'):
    try:
        query1 = urllib2.urlopen('http://{0}:{1}/scielobooks_1a/_design/scielobooks/_view/books'.format(api_host, api_port))
    except urllib2.URLError:
        print "Connection refused, please check the script configurations running ./{0} -h".format(os.path.basename(__file__))
        exit()

    jsondocs = json.loads(query1.read())

    books = {}
    for reg in jsondocs['rows']:  # rows e uma array (lista) de registros no JSON
        book = books.setdefault(reg['id'], {})
        book['editor'] = reg['value']['publisher']
        book['year'] = 'not defined'
        if 'year' in reg['value']:
            book['year'] = reg['value']['year'][0:10]

        book['creation_date'] = 'not defined'
        if 'creation_date' in reg['value']:
            book['creation_date'] = reg['value']['creation_date'][0:10]

    return books


def sumarize_by_month(stats):
    sumarized = {}
    for key, value in stats.items():

        month = key[4:10]
        if month:
            if key[:3] == 'htm':
                html_stats = sumarized.setdefault('html', {})
                html_stats.setdefault(month, 0)
                html_stats[month] += value

            if key[:3] == 'pdf':
                pdf_stats = sumarized.setdefault('pdf', {})
                pdf_stats.setdefault(month, 0)
                pdf_stats[month] += value

            if key[:3] == 'epu':
                pdf_stats = sumarized.setdefault('epu', {})
                pdf_stats.setdefault(month, 0)
                pdf_stats[month] += value

    return sumarized


def get_collection(mongodb_host='localhost',
               mongodb_port=27017,
               mongodb_database='bks',
               mongodb_collection='bks'):

    conn = Connection(mongodb_host, mongodb_port)
    db = conn[mongodb_database + "_accesslog"]
    coll = db[mongodb_collection + "_analytics"]

    return coll


def main(*args, **xargs):

    books = get_books(api_host=xargs['api_host'],
                      api_port=int(xargs['api_port']))

    analytics = get_collection(mongodb_host=xargs['mongodb_host'],
                               mongodb_port=int(xargs['mongodb_port']))

    books_stats = analytics.find({'context': 'book'})

    stats_dict = {}
    for stat in books_stats:
        book_code = stat['code'].lower()
        stats_dict[book_code] = sumarize_by_month(stat)

    print "code|publicated at|created at|editor|access type|month access|accesses"
    for book_code, doc_types in stats_dict.items():
        if book_code in books:<commit_msg>Ajustes em script de tabulação de acessos para deixá-lo configurável quanto a ips de api e bases de dados<commit_after>#!/usr/bin/env python
import os
import urllib2
import json
import argparse

import pymongo


def get_books(api_host='localhost', api_port='5984'):
    try:
        query1 = urllib2.urlopen('http://{0}:{1}/scielobooks_1a/_design/scielobooks/_view/books'.format(api_host, api_port))
    except urllib2.URLError:
        print "API connection refused, please check the script configurations running ./{0} -h".format(os.path.basename(__file__))
        exit()

    jsondocs = json.loads(query1.read())

    books = {}
    for reg in jsondocs['rows']:  # rows e uma array (lista) de registros no JSON
        book = books.setdefault(reg['id'], {})
        book['editor'] = reg['value']['publisher']
        book['year'] = 'not defined'
        if 'year' in reg['value']:
            book['year'] = reg['value']['year'][0:10]

        book['creation_date'] = 'not defined'
        if 'creation_date' in reg['value']:
            book['creation_date'] = reg['value']['creation_date'][0:10]

    return books


def sumarize_by_month(stats):
    sumarized = {}
    for key, value in stats.items():

        month = key[4:10]
        if month:
            if key[:3] == 'htm':
                html_stats = sumarized.setdefault('html', {})
                html_stats.setdefault(month, 0)
                html_stats[month] += value

            if key[:3] == 'pdf':
                pdf_stats = sumarized.setdefault('pdf', {})
                pdf_stats.setdefault(month, 0)
                pdf_stats[month] += value

            if key[:3] == 'epu':
                pdf_stats = sumarized.setdefault('epu', {})
                pdf_stats.setdefault(month, 0)
                pdf_stats[month] += value

    return sumarized


def get_collection(mongodb_host='localhost',
               mongodb_port=27017,
               mongodb_database='bks',
               mongodb_collection='bks'):

    try:
        conn = pymongo.Connection(mongodb_host, mongodb_port)
    except pymongo.errors.AutoReconnect:
        print "MongoDB connection refused, please check the script configurations running ./{0} -h".format(os.path.basename(__file__))
        exit()

    db = conn[mongodb_database + "_accesslog"]
    coll = db[mongodb_collection + "_analytics"]

    return coll


def main(*args, **xargs):

    books = get_books(api_host=xargs['api_host'],
                      api_port=int(xargs['api_port']))

    analytics = get_collection(mongodb_host=xargs['mongodb_host'],
                               mongodb_port=int(xargs['mongodb_port']))

    books_stats = analytics.find({'context': 'book'})

    stats_dict = {}
    for stat in books_stats:
        book_code = stat['code'].lower()
        stats_dict[book_code] = sumarize_by_month(stat)

    print "code|publicated at|created at|editor|access type|month access|accesses"
    for book_code, doc_types in stats_dict.items():
        if book_code in books:
{'fraction_non_alphanumeric': 0.13222707423580787, 'fraction_numerical': 0.011703056768558952, 'mean_word_length': 2.6080655324511657, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5085658', 'n_tokens_mistral': 1875, 'n_tokens_neox': 1764, 'n_words': 368}