only_ever_generator 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/.env.example +1 -0
  2. package/dist/bootstrap/app.js +73 -0
  3. package/dist/class/parse/parse_source_content.js +62 -0
  4. package/dist/class/services/open_ai_service.js +25 -0
  5. package/dist/config.js +7 -0
  6. package/dist/constants/prompts/card_gen_prompt.js +269 -0
  7. package/dist/constants/prompts/typology_prompt.js +97 -0
  8. package/dist/constants/source_data.js +22 -0
  9. package/dist/index.js +59 -0
  10. package/dist/parse_response/parse_card_response.js +288 -0
  11. package/dist/parse_response/response_format_card.js +210 -0
  12. package/dist/parse_response/response_format_typology.js +47 -0
  13. package/dist/service/open_ai_request.js +58 -0
  14. package/dist/typology_gen/generate_typology.js +66 -0
  15. package/dist/utils/generate_args.js +37 -0
  16. package/dist/utils/parse_openai_response.js +23 -0
  17. package/package.json +31 -0
  18. package/readme.md +23 -0
  19. package/src/bootstrap/app.ts +78 -0
  20. package/src/class/parse/parse_source_content.ts +71 -0
  21. package/src/class/services/open_ai_service.ts +18 -0
  22. package/src/config.ts +7 -0
  23. package/src/constants/prompts/card_gen_prompt.ts +269 -0
  24. package/src/constants/prompts/typology_prompt.ts +94 -0
  25. package/src/constants/source_data.ts +30 -0
  26. package/src/index.ts +66 -0
  27. package/src/parse_response/parse_card_response.ts +290 -0
  28. package/src/parse_response/response_format_card.ts +211 -0
  29. package/src/parse_response/response_format_typology.ts +44 -0
  30. package/src/service/open_ai_request.ts +46 -0
  31. package/src/typology_gen/generate_typology.ts +57 -0
  32. package/src/utils/generate_args.ts +38 -0
  33. package/src/utils/parse_openai_response.ts +21 -0
  34. package/tsconfig.json +12 -0
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseResponse = exports.returnResponse = void 0;
4
+ const responseData = {
5
+ "flash_cards": [
6
+ {
7
+ "question": "What is the primary function of the 'Electrolysis'?",
8
+ "answer": "Electrolysis is the passing of a direct electric current through an electrolyte producing chemical reactions at the electrodes and decomposition of the materials.",
9
+ "heading": "Overview"
10
+ },
11
+ {
12
+ "question": "What did Michael Faraday discover while studying the process of electrolysis under Humphry Davy?",
13
+ "answer": "Michael Faraday discovered two laws of electrolysis.",
14
+ "heading": "History"
15
+ },
16
+ {
17
+ "question": "What can electrolysis be used for in the manufacturing sector?",
18
+ "answer": "Electrolysis can be used for electroplating and electrochemical machining.",
19
+ "heading": "Manufacturing processes"
20
+ },
21
+ {
22
+ "question": "In the context of electrolysis, what does the term 'Decomposition potential' refer to?",
23
+ "answer": "Decomposition potential or decomposition voltage refers to the minimum voltage between anode and cathode of an electrolytic cell needed for electrolysis to occur.",
24
+ "heading": "Decomposition potential"
25
+ }
26
+ ],
27
+ "mcqs": [
28
+ {
29
+ "question": "What is the primary purpose of 'Electrometallurgy'?",
30
+ "answers": [
31
+ {
32
+ "answer": "Production of aluminium",
33
+ "is_correct": true
34
+ },
35
+ {
36
+ "answer": "Chlorine production",
37
+ "is_correct": false
38
+ },
39
+ {
40
+ "answer": "Purifying copper",
41
+ "is_correct": false
42
+ },
43
+ {
44
+ "answer": "Rust removal",
45
+ "is_correct": false
46
+ },
47
+ {
48
+ "answer": "Hydrogen production",
49
+ "is_correct": false
50
+ }
51
+ ],
52
+ "heading": "Industrial uses"
53
+ },
54
+ {
55
+ "question": "What can electrolysis be used for in the context of batteries?",
56
+ "answers": [
57
+ {
58
+ "answer": "Spontaneous redox reactions",
59
+ "is_correct": true
60
+ },
61
+ {
62
+ "answer": "Energy-releasing reactions",
63
+ "is_correct": false
64
+ },
65
+ {
66
+ "answer": "Disinfectant production",
67
+ "is_correct": false
68
+ },
69
+ {
70
+ "answer": "Fuel production",
71
+ "is_correct": false
72
+ },
73
+ {
74
+ "answer": "Gas diffusion in reactors",
75
+ "is_correct": false
76
+ }
77
+ ],
78
+ "heading": "Related processes"
79
+ }
80
+ ],
81
+ "cloze_cards": [
82
+ {
83
+ "question": "Electrolysis is the passing of a {{c0:direct electric current}} through an {{c1:electrolyte}} producing {{c2:chemical reactions}} at the {{c3:electrodes}} and {{c4:decomposition}} of the materials.",
84
+ "options": [
85
+ {
86
+ "option": "direct electric current",
87
+ "cloze": "c0"
88
+ },
89
+ {
90
+ "option": "electrolyte",
91
+ "cloze": "c1"
92
+ },
93
+ {
94
+ "option": "chemical reactions",
95
+ "cloze": "c2"
96
+ },
97
+ {
98
+ "option": "electrodes",
99
+ "cloze": "c3"
100
+ },
101
+ {
102
+ "option": "decomposition",
103
+ "cloze": "c4"
104
+ },
105
+ {
106
+ "option": "metallic objects",
107
+ "cloze": null
108
+ }
109
+ ]
110
+ },
111
+ {
112
+ "question": "In electrolysis, the decomposition potential or decomposition voltage refers to the minimum voltage between {{c0:anode}} and {{c1:cathode}} of an electrolytic cell needed for electrolysis to occur.",
113
+ "options": [
114
+ {
115
+ "option": "anode",
116
+ "cloze": "c0"
117
+ },
118
+ {
119
+ "option": "cathode",
120
+ "cloze": "c1"
121
+ },
122
+ {
123
+ "option": "electrolyte",
124
+ "cloze": null
125
+ },
126
+ {
127
+ "option": "chemical reactions",
128
+ "cloze": null
129
+ },
130
+ {
131
+ "option": "oxygen",
132
+ "cloze": null
133
+ },
134
+ {
135
+ "option": "hydrogen",
136
+ "cloze": null
137
+ }
138
+ ]
139
+ }
140
+ ]
141
+ };
142
+ function returnResponse() {
143
+ return responseData;
144
+ }
145
+ exports.returnResponse = returnResponse;
146
+ function parseResponse() {
147
+ let cardData = [];
148
+ let data = returnResponse();
149
+ let keys = Object.keys(data);
150
+ if (keys) {
151
+ for (let elem of keys) {
152
+ if (elem == 'flash_cards') {
153
+ cardData.push(...parseFlashCard(data.flash_cards));
154
+ }
155
+ else if (elem == 'cloze_cards') {
156
+ cardData.push(...parseClozeCards(data.cloze_cards));
157
+ }
158
+ else if (elem == 'mcqs') {
159
+ cardData.push(...parseMcq(data.mcqs));
160
+ }
161
+ }
162
+ }
163
+ return cardData;
164
+ }
165
+ exports.parseResponse = parseResponse;
166
+ /// takes array of
167
+ function parseFlashCard(cards) {
168
+ let flashCardData = [];
169
+ for (let elem of cards) {
170
+ flashCardData.push({
171
+ "type": "flash",
172
+ "heading": elem.heading,
173
+ "content": JSON.stringify({
174
+ "front_content": elem.question,
175
+ "back_content": elem.answer
176
+ })
177
+ });
178
+ }
179
+ return flashCardData;
180
+ }
181
+ /// takes array of
182
+ function parseMcq(cardsData) {
183
+ let mcqCards = [];
184
+ for (let elem of cardsData) {
185
+ mcqCards.push({
186
+ "type": "mcq",
187
+ "heading": elem.heading,
188
+ "content": JSON.stringify({
189
+ "question": elem.question,
190
+ "answers": elem.answers
191
+ })
192
+ });
193
+ }
194
+ return mcqCards;
195
+ }
196
+ /// takes array of
197
+ function parseClozeCards(cardsData) {
198
+ let clozeCards = [];
199
+ for (let elem of cardsData) {
200
+ clozeCards.push({
201
+ "type": "cloze",
202
+ "heading": elem.heading,
203
+ "content": JSON.stringify({
204
+ "question": elem.question,
205
+ "options": elem.options
206
+ })
207
+ });
208
+ }
209
+ return clozeCards;
210
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.returnTypologyData = void 0;
4
+ const typologyResponse = {
5
+ "usage_data": {
6
+ "prompt_tokens": 11611,
7
+ "completion_tokens": 441,
8
+ "total_tokens": 12052
9
+ },
10
+ "generated_content": {
11
+ "field": [
12
+ "Sciences",
13
+ "Technology & Engineering",
14
+ "Education, Learning & Personal Development"
15
+ ],
16
+ "concepts": [
17
+ "Electrolysis",
18
+ "Faraday's Laws of Electrolysis",
19
+ "Electrolytic Cell",
20
+ "Decomposition Potential",
21
+ "Oxidation and Reduction at the Electrodes",
22
+ "Electrolysis of Water",
23
+ "Electrolysis of Carbon Dioxide",
24
+ "Electrocrystallization"
25
+ ],
26
+ "facts": [
27
+ "Electrolysis is the passing of a direct electric current through an electrolyte producing chemical reactions at the electrodes and decomposition of the materials.",
28
+ "In electrolysis, the quantity of the products is proportional to the current, and when two or more electrolytic cells are connected in series to the same power source, the products produced in the cells are proportional to their equivalent weight.",
29
+ "The main components required to achieve electrolysis are an electrolyte, electrodes, and an external power source.",
30
+ "Faraday's laws of electrolysis detail the amount of the products of electrolysis is related to the number of electrons in the reaction at the electrodes.",
31
+ "Decomposition potential or decomposition voltage refers to the minimum voltage between anode and cathode of an electrolytic cell that is needed for electrolysis to occur.",
32
+ "The electrochemical reduction of carbon dioxide can produce value-added chemicals such as methane, ethylene, and ethanol."
33
+ ],
34
+ "generate_cards": true,
35
+ "summary_cards": [
36
+ "Electrolysis is the process of passing direct electric current through an electrolyte, resulting in chemical reactions and the decomposition of materials.",
37
+ "Faraday's laws of electrolysis determine the relationship between the amounts of products generated and the electrons involved in the reaction at the electrodes.",
38
+ "Decomposition potential is the minimum voltage required between anode and cathode for electrolysis to occur.",
39
+ "The electrochemical reduction of carbon dioxide is a potential method for producing valuable chemicals such as methane, ethylene, and ethanol."
40
+ ]
41
+ },
42
+ "generated_at": "Tue, 20 Jan 1970 21:17:46 GMT"
43
+ };
44
+ function returnTypologyData() {
45
+ return typologyResponse;
46
+ }
47
+ exports.returnTypologyData = returnTypologyData;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.openAIRequest = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const parse_openai_response_js_1 = require("../utils/parse_openai_response.js");
18
+ function openAIRequest(content, prompt, token, model) {
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ try {
21
+ let message = [
22
+ {
23
+ "role": "system", "content": prompt
24
+ }, {
25
+ "role": "user", "content": content
26
+ }
27
+ ];
28
+ const url = 'https://api.openai.com/v1/chat/completions';
29
+ let response = yield axios_1.default.post(url,
30
+ //data
31
+ {
32
+ "model": model,
33
+ "messages": message,
34
+ "response_format": { "type": "json_object" },
35
+ },
36
+ ///config
37
+ {
38
+ headers: {
39
+ Authorization: "Bearer " + token,
40
+ "Content-Type": ['application/json']
41
+ },
42
+ });
43
+ if (response.status == 200) {
44
+ console.log('success');
45
+ return (0, parse_openai_response_js_1.parseOpenAiSuccessResponse)(response.data);
46
+ // return JSON.parse(response.data.choices[0].message.content);
47
+ }
48
+ else {
49
+ console.log('failed');
50
+ return response.statusText;
51
+ }
52
+ }
53
+ catch (err) {
54
+ return (0, parse_openai_response_js_1.parseOpenAiFailureResponse)(err.response);
55
+ }
56
+ });
57
+ }
58
+ exports.openAIRequest = openAIRequest;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.GenerateTypology = void 0;
13
+ class GenerateTypology {
14
+ constructor(openAiService, prompt, content) {
15
+ this.prompt = '';
16
+ this.content = '';
17
+ this.openAiService = openAiService;
18
+ this.prompt = prompt;
19
+ this.content = content;
20
+ }
21
+ generate() {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ var _a;
24
+ const response = yield ((_a = this.openAiService) === null || _a === void 0 ? void 0 : _a.sendRequest(this.prompt, this.content));
25
+ response['type'] = 'typology';
26
+ response.metadata = {
27
+ "req_time": response.created_at,
28
+ "req_type": response.type,
29
+ "req_tokens": response.usage_data.prompt_tokens,
30
+ "res_tokens": response.usage_data.completion_tokens,
31
+ };
32
+ if (response.status_code == 200) {
33
+ return this.parseTypologyOnSuccess(response);
34
+ }
35
+ else {
36
+ return response;
37
+ }
38
+ });
39
+ }
40
+ parseTypologyOnSuccess(responseData) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ responseData.metadata.status = "completed";
43
+ const generatedContent = responseData.generated_content;
44
+ return {
45
+ status_code: 200,
46
+ metadata: responseData.metadata,
47
+ field: generatedContent.field,
48
+ concepts: generatedContent.concepts,
49
+ facts: generatedContent.facts,
50
+ generate_cards: generatedContent.generate_cards,
51
+ summary_cards: generatedContent.summary_cards,
52
+ type: responseData.type,
53
+ };
54
+ });
55
+ }
56
+ parseTypologyOnFailure(responseData) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ responseData.metadata.status = 'failed';
59
+ return {
60
+ status_code: responseData.status_code,
61
+ metadata: responseData.metadata,
62
+ };
63
+ });
64
+ }
65
+ }
66
+ exports.GenerateTypology = GenerateTypology;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GenerateArgs = void 0;
4
+ class GenerateArgs {
5
+ constructor(generate_card, generate_typology, generate_summary, prompts = {
6
+ typology_prompt: '',
7
+ card_gen_prompt: '',
8
+ summary_prompt: ''
9
+ }) {
10
+ this.generate_card = false;
11
+ this.generate_typology = false;
12
+ this.generate_summary = false;
13
+ this.prompts = {
14
+ typology_prompt: '',
15
+ card_gen_prompt: '',
16
+ summary_prompt: ''
17
+ };
18
+ this.generate_card = generate_card;
19
+ this.generate_typology = generate_typology;
20
+ this.generate_summary = generate_summary;
21
+ this.prompts = prompts;
22
+ }
23
+ getWhatNeedsToBeGenerated() {
24
+ let returnData = [];
25
+ if (this.generate_typology == true) {
26
+ returnData.push('generate_tyopology');
27
+ }
28
+ if (this.generate_summary == true) {
29
+ returnData.push('generate_summary');
30
+ }
31
+ if (this.generate_card == true) {
32
+ returnData.push('generate_card');
33
+ }
34
+ return returnData;
35
+ }
36
+ }
37
+ exports.GenerateArgs = GenerateArgs;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseOpenAiFailureResponse = exports.parseOpenAiSuccessResponse = void 0;
4
+ function parseOpenAiSuccessResponse(responseData) {
5
+ let choices = JSON.parse(responseData.choices[0].message.content);
6
+ let usuage = responseData.usage;
7
+ let createdTime = responseData.created;
8
+ return {
9
+ 'status_code': 200,
10
+ 'usage_data': usuage,
11
+ 'generated_content': choices,
12
+ 'generated_at': createdTime
13
+ };
14
+ }
15
+ exports.parseOpenAiSuccessResponse = parseOpenAiSuccessResponse;
16
+ function parseOpenAiFailureResponse(errorResponse) {
17
+ let usuage = errorResponse.usuage;
18
+ // let statusCode =
19
+ return {
20
+ 'status_code': errorResponse.status,
21
+ };
22
+ }
23
+ exports.parseOpenAiFailureResponse = parseOpenAiFailureResponse;
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "only_ever_generator",
3
+ "version": "0.0.1",
4
+ "main": "dist/index.js",
5
+ "scripts": {
6
+ "start": "nodemon dist/index.js",
7
+ "build": "tsc",
8
+ "test": "echo \"Error: no test specified\" && exit 1"
9
+ },
10
+ "keywords": [],
11
+ "author": "shree",
12
+ "license": "ISC",
13
+ "devDependencies": {
14
+ "@types/express": "^4.17.21",
15
+ "@types/node": "^20.14.2",
16
+ "nodemon": "^3.1.3",
17
+ "ts-node": "^10.9.2",
18
+ "typescript": "^5.4.5"
19
+ },
20
+ "dependencies": {
21
+ "axios": "^1.7.2",
22
+ "dotenv": "^16.4.5",
23
+ "express": "^4.19.2"
24
+ },
25
+ "eslintConfig": {
26
+ "parser": "typescript-eslint-parser",
27
+ "plugins": [
28
+ "typescript"
29
+ ]
30
+ }
31
+ }
package/readme.md ADDED
@@ -0,0 +1,23 @@
1
+ This is a NPM package that handles the all the ai generation for _source on OnlyEver.
2
+ The Generation includes, Knowledge Taxonomy , Summary and Test Cards data for the _source.
3
+
4
+ The class [OnlyEverGenerator] is the Entry point for the generation module it has two required fields,
5
+ [api_key] which is open ai token
6
+ [model] open ai model : 'gpt-3.5-turbo-1106'
7
+ [content] source content : Array<BaseBlocks>
8
+
9
+ The [OnlyEverGenerator] currently exposes a main method, [generate] which handles all types of generation and takes a Param
10
+ ```
11
+ generate(generate_typology = false,generate_card = false) method takes two args, generate_typology and generate_cards, which are both boolean.
12
+ For Eg:
13
+ let oeGenerator = new OnlyEverGenerator(
14
+ api_key,
15
+ model,
16
+ [Block1,Block2,Block3], // oe content model
17
+ );
18
+
19
+
20
+ let responsesArray = await oeGenerator.generate(true,true);
21
+
22
+
23
+ ```
@@ -0,0 +1,78 @@
1
+ import { ParseSourceContent } from "../class/parse/parse_source_content";
2
+ import { OpenAiService } from "../class/services/open_ai_service";
3
+ import { returnCardGenPrompt } from "../constants/prompts/card_gen_prompt";
4
+ import { returnTypologyPrompt } from "../constants/prompts/typology_prompt";
5
+ import { GenerateTypology } from "../typology_gen/generate_typology";
6
+ import { GenerateArgs } from "../utils/generate_args";
7
+
8
+ export class OnlyEverGenerator{
9
+ public api_key: string = '';
10
+ public openAiService: OpenAiService;
11
+ parsedContent: string = '';
12
+ constructor(apiKey:string, model: string, content: Array<any>){
13
+ this.api_key = apiKey;
14
+ this.openAiService = new OpenAiService(apiKey,model ?? 'gpt-3.5-turbo-1106');
15
+ this.parsedContent = new ParseSourceContent(content).parse();
16
+ };
17
+
18
+ typologyResponse = {};
19
+ cardgenResponse = {};
20
+ summarizeResponse = {};
21
+
22
+
23
+
24
+
25
+ async generate(
26
+ generate_card : boolean = false,
27
+ generate_typology: boolean =false,
28
+ ): Promise<Array<any>> {
29
+ let typologyPrompt = returnTypologyPrompt();
30
+ let cardPrompt = returnCardGenPrompt();
31
+ let args = new GenerateArgs(
32
+ generate_card,
33
+ generate_typology,
34
+ false,
35
+ {
36
+ typology_prompt: typologyPrompt,
37
+ card_gen_prompt: cardPrompt,
38
+ summary_prompt: ''
39
+ },
40
+
41
+ );
42
+ const responseToReturn = [];
43
+ const whatNeedsToBeGenerated = args.getWhatNeedsToBeGenerated();
44
+ for(let elem of whatNeedsToBeGenerated)
45
+ if(elem == 'generate_tyopology'){
46
+ this.typologyResponse = await this.generateTypology(args.prompts.typology_prompt ?? '');
47
+ responseToReturn.push(this.typologyResponse);
48
+ }else if(elem == 'generate_card'){
49
+
50
+ this.cardgenResponse = await this.generateCard(args.prompts.card_gen_prompt ?? '', this.parsedContent + JSON.stringify(this.typologyResponse));
51
+ responseToReturn.push(this.cardgenResponse);
52
+ }
53
+
54
+ return responseToReturn;
55
+
56
+ }
57
+
58
+ _returnParsedContent(){
59
+ return this.parsedContent;
60
+ }
61
+
62
+
63
+ async generateCard(prompt: string, content: string){
64
+ let response = await this.openAiService?.sendRequest(prompt,this.parsedContent);
65
+ response['type'] = 'card_gen';
66
+ return response;
67
+ }
68
+
69
+ async generateTypology(prompt:string){
70
+ let response = await new GenerateTypology(
71
+ this.openAiService,
72
+ prompt,
73
+ this.parsedContent
74
+ ).generate();
75
+ return response;
76
+ }
77
+
78
+ }
@@ -0,0 +1,71 @@
1
+ export class ParseSourceContent{
2
+ public content: Array<any>;
3
+
4
+ titles_to_remove = ['See also', 'References', 'Further reading', 'External links', 'Notes and references', 'Bibliography', 'Notes', 'Cited sources'];
5
+
6
+ constructor(sourceContent:Array<any>){
7
+ this.content = sourceContent;
8
+ }
9
+
10
+ parse() {
11
+ let dataAfterRemovingUnWantedBlocks = this.removeSectionsByTitle(this.content);
12
+ let afterSanitized = this.sanitizeBlocks(dataAfterRemovingUnWantedBlocks);
13
+ return JSON.stringify(afterSanitized);
14
+ }
15
+
16
+ removeSectionsByTitle(data: Array<any>){
17
+ let dataAfterRemoving = [];
18
+ for(let elem of data){
19
+ if(elem.block_type == 'heading' && this.titles_to_remove.includes(elem.content)){
20
+ continue;
21
+ }
22
+ if(elem.children){
23
+ elem.children = this.removeSectionsByTitle(elem.children)
24
+ }
25
+ dataAfterRemoving.push(elem)
26
+
27
+ }
28
+ return dataAfterRemoving;
29
+ }
30
+
31
+
32
+ sanitizeWikiContent(content: String) {
33
+ // Remove newline characters
34
+ content = content.replace(/\\n/g, ' ');
35
+
36
+ // Remove internal link references, keeping only the link text
37
+ // Pattern explanation: [[link|text|index|wiki]] --> text
38
+ content = content.replace(/\[\[.*?\|(.*?)\|.*?\|wiki\]\]/g, '$1');
39
+
40
+ // Remove external links, keeping only the link text
41
+ // Pattern explanation: [url text] --> text
42
+ content = content.replace(/\[http[s]?:\/\/[^\s]+ ([^\]]+)\]/g, '$1');
43
+
44
+ // Remove Markdown link references, keeping only the link text
45
+ // Pattern explanation: ![link text](url) --> link text
46
+ content = content.replace(/\!\[([^\]]+)\]\([^\)]+\)/g, '$1');
47
+
48
+ return content;
49
+ }
50
+
51
+ sanitizeBlocks(blocks: Array<any>) {
52
+ let sanitizedBlocks = <any>[] ;
53
+ blocks.forEach(block => {
54
+ let sanitizedBlock: any = {};
55
+ for (let key in block) {
56
+ let value = block[key];
57
+ if (typeof value === 'string') {
58
+ sanitizedBlock[key] = this.sanitizeWikiContent(value);
59
+ } else if (Array.isArray(value)) {
60
+ sanitizedBlock[key] = this.sanitizeBlocks(value);
61
+ } else {
62
+ sanitizedBlock[key] = value;
63
+ }
64
+ }
65
+ sanitizedBlocks.push(sanitizedBlock);
66
+ });
67
+ return sanitizedBlocks;
68
+ }
69
+
70
+
71
+ }
@@ -0,0 +1,18 @@
1
+ import { openAIRequest } from "../../service/open_ai_request";
2
+
3
+
4
+ export class OpenAiService{
5
+ public api_key: string;
6
+ public model: string;
7
+
8
+
9
+ constructor(apiKey: string, model:string){
10
+ this.api_key = apiKey;
11
+ this.model =model
12
+ }
13
+
14
+ async sendRequest(prompt: string,content: string){
15
+ return await openAIRequest(content,prompt,this.api_key,this.model);
16
+ }
17
+ }
18
+
package/src/config.ts ADDED
@@ -0,0 +1,7 @@
1
+ import "dotenv/config";
2
+
3
+ const config = {
4
+ openAIKey : process.env.OPEN_AI_KEY as string
5
+ }
6
+
7
+ export default config;