<commit_before>import os.path
import sys
from pprint import PrettyPrinter
import rouge_calculator
from timeout import TimeoutError, timeout

# Imports files from a parent directory.
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'textrank'))
from textrank import textrank

TEMP_DIRECTORY = rouge_calculator.MODEL_DIRECTORY
TEMP_FILENAME = rouge_calculator.MODEL_FILENAME

RESULTS = {'runs': 0, 'successes': 0, 'timeouts': 0, 'errors': 0, 'reports': []}

@timeout(10)
def summarize_text(filename):
    # pyrouge needs the model summaries to be stored in a directory without subdirectories.
    if not os.path.exists(TEMP_DIRECTORY):
        os.makedirs(TEMP_DIRECTORY)

    # Makes a summary of the provided file and stores it in the temp folder.
    with open(filename) as fp:
        text = fp.read()

    print "Summarizing " + filename
    summary = textrank(text)

    with open(os.path.join(TEMP_DIRECTORY, TEMP_FILENAME), 'w') as fp:
        fp.write(summary)


def get_rouge_summary_for_text(text_number):
    text_filename = 'datasets/elhadad/{text_number:02d}/text.txt'.format(text_number=text_number)
    gold_references_dir = 'datasets/elhadad/{text_number:02d}'.format(text_number=text_number)
    summarize_text(text_filename)
    return rouge_calculator.evaluate_summary(gold_references_dir, 'summ(\d+).txt')


for i in range(1, 25):
    print "Evaluating set #" + str(i)

    RESULTS['runs'] += 1
    try:
        result = get_rouge_summary_for_text(i)
    except TimeoutError:
        print "Timeout summarizing text #" + str(i)
        RESULTS['timeouts'] += 1
        continue
    except:
        print "Error summarizing text #" + str(i)
        RESULTS['errors'] += 1
        continue

    print "Text #%d summarized successfully" % i
    RESULTS['successes'] += 1
    RESULTS['reports'].append(result)

successes = float(RESULTS['successes'])

avg_rouge1_fscore = sum(result['rouge_1_f_score'] for result in RESULTS['reports']) / successes
print "Average F-score for ROUGE-1 metric: " + str(avg_rouge1_fscore)

avg_rouge2_fscore = sum(result['rouge_2_f_score'] for result in RESULTS['reports']) / successes
print "Average F-score for ROUGE-2 metric: " + str(avg_rouge2_fscore)

avg_su_fscore = sum(result['rouge_su*_f_score'] for result in RESULTS['reports']) / successes
print "Average F-score for ROUGE-SU metric: " + str(avg_su_fscore)
<commit_msg>Adding command line arguments support.<commit_after>import os.path
import sys
from pprint import PrettyPrinter
import rouge_calculator
from timeout import TimeoutError, timeout

# Imports files from a parent directory.
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'textrank'))
from textrank import textrank

TEMP_DIRECTORY = rouge_calculator.MODEL_DIRECTORY
TEMP_FILENAME = rouge_calculator.MODEL_FILENAME

RESULTS = {'runs': 0, 'successes': 0, 'timeouts': 0, 'errors': 0, 'reports': []}

@timeout(10)
def summarize_text(filename):
    # pyrouge needs the model summaries to be stored in a directory without subdirectories.
    if not os.path.exists(TEMP_DIRECTORY):
        os.makedirs(TEMP_DIRECTORY)

    # Makes a summary of the provided file and stores it in the temp folder.
    with open(filename) as fp:
        text = fp.read()

    print "Summarizing " + filename
    summary = textrank(text)

    with open(os.path.join(TEMP_DIRECTORY, TEMP_FILENAME), 'w') as fp:
        fp.write(summary)


def get_rouge_summary_for_text(text_number):
    text_filename = 'datasets/elhadad/{text_number:02d}/text.txt'.format(text_number=text_number)
    gold_references_dir = 'datasets/elhadad/{text_number:02d}'.format(text_number=text_number)
    summarize_text(text_filename)
    return rouge_calculator.evaluate_summary(gold_references_dir, 'summ(\d+).txt')


def get_rouge_scores(dataset_numbers):
    for i in dataset_numbers:
        print "Evaluating set #" + str(i)

        RESULTS['runs'] += 1
        try:
            result = get_rouge_summary_for_text(i)
        except TimeoutError:
            print "Timeout summarizing text #" + str(i)
            RESULTS['timeouts'] += 1
            continue
        except:
            print "Error summarizing text #" + str(i)
            RESULTS['errors'] += 1
            continue

        print "Text #%d summarized successfully" % i
        RESULTS['successes'] += 1
        RESULTS['reports'].append(result)

    successes = float(RESULTS['successes'])

    avg_rouge1_fscore = sum(result['rouge_1_f_score'] for result in RESULTS['reports']) / successes
    print "Average F-score for ROUGE-1 metric: " + str(avg_rouge1_fscore)

    avg_rouge2_fscore = sum(result['rouge_2_f_score'] for result in RESULTS['reports']) / successes
    print "Average F-score for ROUGE-2 metric: " + str(avg_rouge2_fscore)

    avg_su_fscore = sum(result['rouge_su*_f_score'] for result in RESULTS['reports']) / successes
    print "Average F-score for ROUGE-SU metric: " + str(avg_su_fscore)


if __name__ == '__main__':
    # Calculate all rouge scores if no argument is provided.
    if len(sys.argv) == 1:
        get_rouge_scores(xrange(1, 25))

    # Else calculate rouge scores for the specified datasets.
    else:
        get_rouge_scores([int(x) for x in sys.argv[1:]])


{'fraction_non_alphanumeric': 0.11049933548509588, 'fraction_numerical': 0.009872792861211316, 'mean_word_length': 3.9604519774011298, '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': '44927', 'n_tokens_mistral': 1845, 'n_tokens_neox': 1705, 'n_words': 416}