-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdata_gen.py
More file actions
100 lines (86 loc) · 3.18 KB
/
Copy pathdata_gen.py
File metadata and controls
100 lines (86 loc) · 3.18 KB
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
from openai import OpenAI
from pydantic import BaseModel
from typing import List
import json
import os
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env file
openai_key=os.getenv("OPENAI_API_KEY")
if not openai_key:
raise ValueError("OPENAI_API_KEY not found in environment variables.")
# -------------------------------
# Initialize OpenAI client
# -------------------------------
# Make sure OPENAI_API_KEY is set in your environment before running
client=OpenAI(api_key=openai_key)
# -------------------------------
# Define Structured Output Schema
# -------------------------------
class Triplet(BaseModel):
base: str
looks_similar: str
looks_different: str
explanation: str
class TripletBatch(BaseModel):
domain: str
triplets: List[Triplet]
# -------------------------------
# Load Prompt from Markdown File
# -------------------------------
def load_prompt(filepath: str) -> str:
with open(filepath, "r", encoding="utf-8") as f:
return f.read()
# -------------------------------
# Generate Triplets (Single Batch)
# -------------------------------
def generate_triplets(prompt_text: str) -> TripletBatch:
response = client.responses.parse(
model="gpt-4.1",
input=[
{
"role": "system",
"content": (
"You are a linguistic data generator. "
"Produce high-quality semantic stress-test triplets "
"that distinguish word-level from meaning-level embeddings."
),
},
{"role": "user", "content": prompt_text},
],
text_format=TripletBatch,
)
return response.output_parsed
# -------------------------------
# Generate Multiple Batches & Stream Save
# -------------------------------
def generate_and_save(prompt_path: str, n_batches: int, output_file: str):
prompt = load_prompt(prompt_path)
# Open file in append mode so data is written immediately
with open(output_file, "a", encoding="utf-8") as f:
for i in range(1, n_batches + 1):
print(f"🔹 Generating batch {i}/{n_batches}...")
try:
batch = generate_triplets(prompt)
except Exception as e:
print(f"⚠️ Error on batch {i}: {e}")
continue # Skip failed batch and move on
for t in batch.triplets:
triplet_dict = {
"Base": t.base,
"Looks Similar": t.looks_similar,
"Looks Different": t.looks_different,
"Explanation": t.explanation,
}
json.dump(triplet_dict, f, ensure_ascii=False)
f.write("\n")
f.flush() # Write immediately, don’t buffer
print(f"✅ Saved batch {i} to file (streamed).")
print(f"\n🎯 All done! {n_batches} batches written to '{output_file}'")
# -------------------------------
# Main
# ------------------------------
if __name__ == "__main__":
generate_and_save(
prompt_path="software_repo_desc/software_gen_triplet.md",
n_batches=100,
output_file="software_repo_desc/triplets.jsonl")