-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_dataset.py
More file actions
125 lines (74 loc) · 1.97 KB
/
Copy pathgenerate_dataset.py
File metadata and controls
125 lines (74 loc) · 1.97 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
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
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from openai import OpenAI
import os
from dotenv import load_dotenv
import json
from tqdm import tqdm
load_dotenv()
client = OpenAI(api_key = os.getenv("METIS_API_KEY") ,
base_url="https://api.metisai.ir/openai/v1")
pdf_path = "data/book.pdf"
loader = PyPDFLoader(pdf_path)
documents = loader.load()
splitter = RecursiveCharacterTextSplitter(
chunk_size = 1000,
chunk_overlap = 200
)
chunks = splitter.split_documents(documents)
def create_prompt(text):
prompt = f"""
You are a dataset Generator.
Convert the following text into Alpaca instruction format.
Rules:
-Return ONLY JSON
-No markdown
-No Explanation
Each item must contain:
instruction
input
output
Generate 5 examples
text :
{text}
"""
return prompt
def generate_examples(text):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role":"user",
"content":create_prompt(text)
}
],
temperature=0.3
)
return response.choices[0].message.content
def clean_json(output):
output = output.replace("```json","")
output = output.replace("```","")
output = output.strip()
return json.loads(output)
dataset = []
for chunk in tqdm(chunks):
text = chunk.page_content
try:
result = generate_examples(text)
examples = clean_json(result)
dataset.extend(examples)
except Exception as e:
print("Error : ", e)
with open(
"output/alpaca.json",
"w",
encoding="utf-8"
) as f:
json.dump(dataset,f,indent=2,ensure_ascii=False)
print(
"Dataset Size : ",
len(dataset)
)
print("Number of chunks : ", len(chunks))
print("Pages : ",len(documents))
print(documents[0].page_content[:500])