File size: 17,081 Bytes
314657b
3e5de7a
314657b
3e5de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
058ded2
3e5de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314657b
3e5de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
058ded2
3e5de7a
058ded2
3e5de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314657b
 
3e5de7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import os
import argparse
import json
import numpy as np
from tqdm import tqdm
import nltk
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from rouge import Rouge
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import re
from textstat import flesch_reading_ease
from datasets import load_dataset
import openai
import time
from datetime import datetime
import google.generativeai as genai
import traceback

SLEEP_INTERVAL = 30

nltk.download('punkt', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)

def create_client(model_name, base_url):
    if model_name.lower().startswith('gemini'):
        api_key = os.getenv("GOOGLE_API_KEY")
        if not api_key:
            raise ValueError("GOOGLE_API_KEY environment variable is not set")
        genai.configure(api_key=api_key)
        return 'gemini'
    else:
        api_key = os.getenv("OPENAI_API_KEY")
        if not api_key:
            raise ValueError("OPENAI_API_KEY environment variable is not set")
        return openai.OpenAI(api_key=api_key) if base_url is None else openai.OpenAI(api_key=api_key, base_url=base_url)

def preprocess(text):
    return nltk.word_tokenize(text.lower())

def calculate_bleu(reference, candidate):
    reference_tokens = preprocess(reference)
    candidate_tokens = preprocess(candidate)
    smoothie = SmoothingFunction().method1
    return sentence_bleu([reference_tokens], candidate_tokens, smoothing_function=smoothie)

def calculate_rouge(reference, candidate):
    rouge = Rouge()
    scores = rouge.get_scores(candidate, reference)
    return {
        'rouge-1': scores[0]['rouge-1']['f'],
        'rouge-2': scores[0]['rouge-2']['f'],
        'rouge-l': scores[0]['rouge-l']['f']
    }

def calculate_cosine_similarity(reference, candidate):
    vectorizer = TfidfVectorizer()
    tfidf_matrix = vectorizer.fit_transform([reference, candidate])
    return cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:2])[0][0]

def extract_sections(readme):
    sections = []
    current_section = ""
    for line in readme.split('\n'):
        if line.strip().startswith('#'):
            if current_section:
                sections.append(current_section.strip())
            current_section = line + "\n"
        else:
            current_section += line + "\n"
    if current_section:
        sections.append(current_section.strip())
    return sections

def calculate_structural_similarity(reference, candidate):
    ref_sections = extract_sections(reference)
    cand_sections = extract_sections(candidate)
    
    # Calculate section difference
    max_sections = max(len(ref_sections), len(cand_sections))
    section_diff = abs(len(ref_sections) - len(cand_sections))
    section_similarity = 1 - (section_diff / max_sections) if max_sections > 0 else 0
    
    # Calculate title similarity
    ref_titles = [s.split('\n')[0] for s in ref_sections]
    cand_titles = [s.split('\n')[0] for s in cand_sections]
    title_similarity = len(set(ref_titles) & set(cand_titles)) / max(len(ref_titles), len(cand_titles)) if ref_titles or cand_titles else 0
    
    # Combine section and title similarity
    structural_similarity = (section_similarity + title_similarity) / 2
    
    return structural_similarity

def information_retrieval_score(readme):
    key_sections = ['installation', 'usage', 'api', 'example', 'license']
    found_sections = sum(1 for section in key_sections if section in readme.lower())
    return found_sections / len(key_sections)

def code_readme_consistency(repo_content, readme):
    code_elements = set(re.findall(r'def\s+(\w+)', repo_content) + 
                        re.findall(r'class\s+(\w+)', repo_content))
    
    mentioned_elements = sum(1 for element in code_elements if element in readme)
    
    return mentioned_elements / len(code_elements) if code_elements else 0

def calculate_readability(text):
    return flesch_reading_ease(text) / 100

def evaluate_readme(reference_readme, generated_readme, repo_content):
    bleu_score = calculate_bleu(reference_readme, generated_readme)
    rouge_scores = calculate_rouge(reference_readme, generated_readme)
    cosine_sim = calculate_cosine_similarity(reference_readme, generated_readme)
    structural_sim = calculate_structural_similarity(reference_readme, generated_readme)
    info_retrieval = information_retrieval_score(generated_readme)
    code_consistency = code_readme_consistency(repo_content, generated_readme)
    readability = calculate_readability(generated_readme)
    
    weights = {
        'bleu': 0.1,
        'rouge-1': 0.033,
        'rouge-2': 0.033,
        'rouge-l': 0.034,
        'cosine_similarity': 0.1,
        'structural_similarity': 0.1,
        'information_retrieval': 0.2,
        'code_consistency': 0.2,
        'readability': 0.2
    }
    
    weighted_score = (
        weights['bleu'] * bleu_score +
        weights['rouge-1'] * rouge_scores['rouge-1'] +
        weights['rouge-2'] * rouge_scores['rouge-2'] +
        weights['rouge-l'] * rouge_scores['rouge-l'] +
        weights['cosine_similarity'] * cosine_sim +
        weights['structural_similarity'] * structural_sim +
        weights['information_retrieval'] * info_retrieval +
        weights['code_consistency'] * code_consistency +
        weights['readability'] * readability
    )
    
    return {
        'bleu': bleu_score,
        'rouge': rouge_scores,
        'cosine_similarity': cosine_sim,
        'structural_similarity': structural_sim,
        'information_retrieval': info_retrieval,
        'code_consistency': code_consistency,
        'readability': readability,
        'weighted_score': weighted_score
    }

def generate_readme_openai(repo_content, model, client):
    system_prompt = """You are an AI assistant tasked with creating a README.md file for a GitHub repository. 
    Your response should contain ONLY the content of the README.md file, without any additional explanations or markdown code blocks. 
    The README should include the following sections:
    1. Project Title
    2. Description
    3. Installation
    4. Usage
    5. Features
    6. Contributing
    7. License
    Ensure that your response is well-structured, informative, and directly usable as a README.md file."""

    user_prompt = f"Here is the content of the repository:\n\n{repo_content}\n\nBased on this content, please generate a README.md file."

    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ]
    )
    
    return response.choices[0].message.content

def generate_readme_gemini(repo_content, model):
    safe = [
    {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_NONE",
    },
    {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_NONE",
    },
    {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_NONE",
    },
    {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_NONE",
    },
    ]
    prompt = f"""Create a README.md file for a GitHub repository based on the following repository content. 
    Your response should contain ONLY the content of the README.md file, without any additional explanations or markdown code blocks. 
    The README should include the following sections:
    1. Project Title
    2. Description
    3. Installation
    4. Usage
    5. Features
    6. Contributing
    7. License
    Ensure that your response is well-structured, informative, and directly usable as a README.md file.

    Repository content:

    {repo_content}
    """

    model = genai.GenerativeModel(model,safety_settings=safe)
    response = model.generate_content(prompt)
    
    return response.text

def generate_readme(repo_content, model_name, client):
    if client == 'gemini':
        return generate_readme_gemini(repo_content, model_name)
    else:
        return generate_readme_openai(repo_content, model_name, client)

def main(args):
    dataset = load_dataset("patched-codes/generate-readme-eval")
    
    results = []

    if args.generate_fine_tune_jsonl:
        output_file = f"fine_tune_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jsonl"
        generate_fine_tune_jsonl(dataset, output_file)
        print(f"Fine-tune JSONL file generated: {output_file}")
        return
    
    if args.oracle:
        model_name = "oracle"
    else:
        model_name = args.model
        client = create_client(model_name, args.base_url)

    for item in tqdm(dataset['test'], desc="Processing repos"):
        try:
            if args.oracle:
                # Use the existing README as both reference and generated
                generated_readme = item['repo_readme']
            elif args.n_shot > 0:
                generated_readme = generate_readme_n_shot(item['repo_content'], model_name, client, dataset['train'], args.n_shot)
            else:
                generated_readme = generate_readme(item['repo_content'], model_name, client)
            
            eval_result = evaluate_readme(item['repo_readme'], generated_readme, item['repo_content'])
            eval_result['repo_name'] = item['repo_name']
            results.append(eval_result)
        except Exception as e:
            print(f"Error processing repo {item['repo_name']}: {e}")
            continue
        if model_name.lower().startswith('gemini'):
            time.sleep(SLEEP_INTERVAL)
    
    average_scores = {
        'bleu': np.mean([r['bleu'] for r in results]),
        'rouge-1': np.mean([r['rouge']['rouge-1'] for r in results]),
        'rouge-2': np.mean([r['rouge']['rouge-2'] for r in results]),
        'rouge-l': np.mean([r['rouge']['rouge-l'] for r in results]),
        'cosine_similarity': np.mean([r['cosine_similarity'] for r in results]),
        'structural_similarity': np.mean([r['structural_similarity'] for r in results]),
        'information_retrieval': np.mean([r['information_retrieval'] for r in results]),
        'code_consistency': np.mean([r['code_consistency'] for r in results]),
        'readability': np.mean([r['readability'] for r in results]),
        'weighted_score': np.mean([r['weighted_score'] for r in results])
    }
    
    # Print results to console
    print("\nEvaluation Results:")
    for metric, score in average_scores.items():
        print(f"{metric}: {score:.4f}")

    # Save results to log file
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    log_filename = f"{model_name}_results_{timestamp}.log"
    
    with open(log_filename, 'w') as log_file:
        log_file.write(f"Evaluation Results for model: {model_name}\n")
        log_file.write(f"Timestamp: {timestamp}\n\n")
        log_file.write("Average Scores:\n")
        for metric, score in average_scores.items():
            log_file.write(f"{metric}: {score:.4f}\n")
        
        log_file.write(f"\nDetailed Results:\n")
        for result in results:
            log_file.write(f"\nRepository: {result['repo_name']}\n")
            log_file.write("Scores:\n")
            log_file.write(f"  BLEU: {result['bleu']:.4f}\n")
            log_file.write(f"  ROUGE-1: {result['rouge']['rouge-1']:.4f}\n")
            log_file.write(f"  ROUGE-2: {result['rouge']['rouge-2']:.4f}\n")
            log_file.write(f"  ROUGE-L: {result['rouge']['rouge-l']:.4f}\n")
            log_file.write(f"  Cosine Similarity: {result['cosine_similarity']:.4f}\n")
            log_file.write(f"  Structural Similarity: {result['structural_similarity']:.4f}\n")
            log_file.write(f"  Information Retrieval: {result['information_retrieval']:.4f}\n")
            log_file.write(f"  Code Consistency: {result['code_consistency']:.4f}\n")
            log_file.write(f"  Readability: {result['readability']:.4f}\n")
            log_file.write(f"  Weighted Score: {result['weighted_score']:.4f}\n")

    print(f"\nResults saved to {log_filename}")

def generate_fine_tune_jsonl(dataset, output_file):
    system_prompt = """You are an AI assistant tasked with creating a README.md file for a GitHub repository. 
    Your response should contain ONLY the content of the README.md file, without any additional explanations or markdown code blocks. 
    The README should include the following sections:
    1. Project Title
    2. Description
    3. Installation
    4. Usage
    5. Features
    6. Contributing
    7. License
    Ensure that your response is well-structured, informative, and directly usable as a README.md file."""

    with open(output_file, 'w') as f:
        for item in tqdm(dataset['train'], desc="Generating fine-tune data"):
            user_prompt = f"Here is the content of the repository:\n\n{item['repo_content']}\n\nBased on this content, please generate a README.md file."
            
            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt},
                {"role": "assistant", "content": item['repo_readme']}
            ]
            
            json.dump({"messages": messages}, f)
            f.write('\n')

def find_similar_examples(repo_content, train_dataset, n):
    vectorizer = TfidfVectorizer()
    train_contents = [item['repo_content'] for item in train_dataset]
    train_vectors = vectorizer.fit_transform(train_contents)
    query_vector = vectorizer.transform([repo_content])
    
    similarities = cosine_similarity(query_vector, train_vectors).flatten()
    top_n_indices = similarities.argsort()[-n:][::-1]
    
    return [train_dataset[int(i)] for i in top_n_indices]

def generate_readme_n_shot(repo_content, model_name, client, train_dataset, n_shot):
    similar_examples = find_similar_examples(repo_content, train_dataset, n_shot)
    
    system_prompt = """You are an AI assistant tasked with creating a README.md file for a GitHub repository. 
    Your response should contain ONLY the content of the README.md file, without any additional explanations or markdown code blocks. 
    The README should include the following sections:
    1. Project Title
    2. Description
    3. Installation
    4. Usage
    5. Features
    6. Contributing
    7. License
    Ensure that your response is well-structured, informative, and directly usable as a README.md file."""

    few_shot_examples = ""
    for example in similar_examples:
        few_shot_examples += f"Repository content:\n\n{example['repo_content']}\n\n"
        few_shot_examples += f"Generated README:\n\n{example['repo_readme']}\n\n---\n\n"

    user_prompt = f"""Here are some examples of repository contents and their corresponding README files:

{few_shot_examples}
Now, here is the content of the repository you need to create a README for:

{repo_content}

Based on this content and the examples provided, please generate a README.md file."""

    if client == 'gemini':
        safe = [
            {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
            {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
            {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
            {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
        ]
        model = genai.GenerativeModel(model_name, safety_settings=safe)
        response = model.generate_content(user_prompt)
        return response.text
    else:
        response = client.chat.completions.create(
            model=model_name,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ]
        )
        return response.choices[0].message.content

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Generate and evaluate README files using OpenAI or Gemini API, or compute oracle scores")
    parser.add_argument("model", nargs='?', help="Model to use (e.g., 'gpt-4o-mini' for OpenAI or 'gemini-1.5-flash' for Google)")
    parser.add_argument("--base_url", help="Optional base URL for OpenAI API", default=None)
    parser.add_argument("--oracle", action="store_true", help="Compute oracle scores using existing READMEs")
    parser.add_argument("--generate-fine-tune-jsonl", action="store_true", help="Generate a JSONL file for fine-tuning")
    parser.add_argument("--n_shot", type=int, default=0, help="Number of examples to use for few-shot learning")
    args = parser.parse_args()
    
    if args.generate_fine_tune_jsonl:
        if args.oracle or args.model:
            parser.error("--generate-fine-tune-jsonl flag cannot be used with --oracle or model specification")
    elif args.oracle and args.model:
        parser.error("--oracle flag cannot be used with a model specification")
    elif not args.oracle and not args.model:
        parser.error("Either --oracle flag or a model name must be provided")
    
    main(args)