Skip to content

Commit 9c65257

Browse files
authored
Removed extra line before main fn (#272)
* Removed extra line before main fn * removed extra line in trainers.py * - Refactored store.js into two files: store.js and codegen.js - fixed code rendering issue with additional new lines
1 parent 46d3daa commit 9c65257

File tree

15 files changed

+94
-70
lines changed

15 files changed

+94
-70
lines changed

.github/workflows/ci.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ jobs:
8282
- run: pnpm build
8383
- run: pnpm test:ci
8484
- run: sh ./scripts/run_tests.sh unzip
85-
- run: pnpm lint
85+
- run: pnpm dist_lint
8686

8787
- name: 'Run ${{ matrix.template }} ${{ matrix.test }}'
8888
run: sh ./scripts/run_tests.sh ${{ matrix.test }} ${{ matrix.template }}
@@ -110,4 +110,4 @@ jobs:
110110
- run: pip install -Uq pip wheel && bash scripts/run_code_style.sh install
111111
- run: npm install -g pnpm
112112
- run: pnpm i --frozen-lockfile --color
113-
- run: pnpm min_lint
113+
- run: pnpm source_lint

CONTRIBUTING.md

+5-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ To contribute to Code-Generator App, you will need Nodejs LTS v16, VSCode, Vetur
2727

2828
- Create a virtual environment for python.
2929

30+
- For docker users please see [this guide](docker/readme.md)
31+
3032
- With pip:
3133

3234
```sh
@@ -104,9 +106,9 @@ To add a new template,
104106

105107
```sh
106108
# format
107-
pnpm run fmt
109+
pnpm fmt
108110
# lint
109-
pnpm run lint
111+
pnpm source_lint
110112
```
111113

112114
- To ensure the codebase complies with a style guide, we use black and ufmt to format and check codebase for compliance with PEP8. Install and run with:
@@ -117,7 +119,7 @@ To add a new template,
117119
# format the codes
118120
bash scripts/run_code_style.sh fmt
119121
# lint the codes
120-
bash scripts/run_code_style.sh lint
122+
bash scripts/run_code_style.sh source_lint
121123
```
122124

123125
_NOTE: Even if you have a half-completed/working PR, sending a PR is still a valid contribution and we can help you finish the PR._

docker/readme.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ pnpm dev
4141
- Run ci tests locally
4242

4343
```bash
44-
pnpm test:ci
44+
pnpm dev &
45+
pnpm test
4546

4647
sh ./scripts/run_tests.sh unzip
4748
sh ./scripts/run_tests.sh simple vision-classification

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
"test:ci": "start-server-and-test --expect 200 serve http://127.0.0.1:5000 test",
1010
"release": "node scripts/release.js",
1111
"fmt": "prettier --write . && bash scripts/run_code_style.sh fmt",
12-
"min_lint": "prettier --check . && bash scripts/run_code_style.sh min_lint",
13-
"lint": "prettier --check . && bash scripts/run_code_style.sh lint"
12+
"source_lint": "prettier --check . && bash scripts/run_code_style.sh source_lint",
13+
"dist_lint": "prettier --check . && bash scripts/run_code_style.sh dist_lint"
1414
},
1515
"dependencies": {
1616
"@iconify/iconify": "^3.1.0",

scripts/run_code_style.sh

+6-2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@
22

33
set -xeu
44

5-
if [ $1 == "lint" ]; then
5+
if [ $1 == "dist_lint" ]; then
66
# Check that ./dist-tests/ exists and code is unzipped
77
ls ./dist-tests/vision-classification-all/main.py
8+
# Comment dist-tests in .gitignore to make black running on ./dist-tests folder
9+
# TODO:
810
ufmt diff .
911
flake8 --select F401,F821 ./dist-tests # find unused imports and non imported objects
10-
elif [ $1 == "min_lint" ]; then
12+
# Restore .gitignore
13+
# TODO:
14+
elif [ $1 == "source_lint" ]; then
1115
ufmt diff .
1216
elif [ $1 == "fmt" ]; then
1317
ufmt format .

src/codegen.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// @ts-check
2+
import ejs from 'ejs'
3+
4+
// merges the code from the common and specific files using ejs
5+
export function mergeCode(specificFileText, commonFileText) {
6+
const replaced = specificFileText.replace(
7+
/#::= from_template_common ::#\n/g,
8+
commonFileText
9+
)
10+
return replaced
11+
}
12+
13+
export function renderCode(code, config) {
14+
// code = code
15+
// .replace(/({ :::#[\n\s]+)/gi, '{ :::#')
16+
// .replace(/([\s\n]+#:::\s}\s:::#)/gi, '#::: } :::#')
17+
18+
// replace `\s(s) or \n(s)#:::\s`
19+
// with `#::: `
20+
code = code.replace(/([\s\n]+#:::\s)/gi, '#::: ')
21+
22+
return ejs.render(code, config).replace(/ # usort: skip/g, '')
23+
}
24+
25+
// render the code if there are fetched files for current selected template
26+
export function generateFiles(currentFiles, store) {
27+
for (const file in currentFiles) {
28+
if (!store.config.include_test && file === 'test_all.py') {
29+
delete store.code['test_all.py']
30+
continue
31+
}
32+
store.code[file] = renderCode(currentFiles[file], store.config)
33+
}
34+
}
35+
36+
// ejs options
37+
ejs.localsName = 'it'
38+
ejs.delimiter = ':::'
39+
ejs.openDelimiter = '#'
40+
ejs.closeDelimiter = '#'

src/store.js

+2-32
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
// @ts-check
22
// central store for user input configs and generated codes
33
import { reactive, watch } from 'vue'
4-
import ejs from 'ejs'
54

65
import templates from './templates/templates.json'
6+
import { generateFiles, mergeCode } from './codegen'
77

88
// get env variables for template fetching
99
// @ts-ignore
@@ -59,36 +59,12 @@ export function saveConfig(key, value) {
5959
}
6060
}
6161

62-
// merges the code from the common and specific files using ejs
63-
function mergeCode(specificFileText, commonFileText) {
64-
const replaced = specificFileText.replace(
65-
/#::= from_template_common ::#\n/g,
66-
commonFileText
67-
)
68-
return replaced
69-
}
70-
7162
// render the code if there are fetched files for current selected template
7263
export function genCode() {
7364
const currentFiles = files[store.config.template]
7465
store.code = {} // empty the `store.code` after changing templates
7566
if (currentFiles && Object.keys(currentFiles).length) {
76-
for (const file in currentFiles) {
77-
if (!store.config.include_test && file === 'test_all.py') {
78-
delete store.code['test_all.py']
79-
continue
80-
}
81-
store.code[file] = ejs
82-
.render(
83-
// replace `\s(s) or \n(s)#:::\s`
84-
// with `#::: `
85-
currentFiles[file].replace(/([\s\n]+#:::\s)/gi, '#::: '),
86-
store.config
87-
)
88-
// trim ` #`
89-
.replace(/\s{4}#$/gim, '')
90-
.replace(/ # usort: skip/g, '')
91-
}
67+
generateFiles(currentFiles, store)
9268
if (isDev) {
9369
store.code[__DEV_CONFIG_FILE__] =
9470
'# THIS FILE APPEARS ONLY IN DEV MODE\n' +
@@ -130,9 +106,3 @@ export async function fetchTemplates(template) {
130106
// if that changed, call the genCode function
131107
// same as watch(() => store.config, () => genCode(), { deep: true })
132108
watch(store.config, () => genCode())
133-
134-
// ejs options
135-
ejs.localsName = 'it'
136-
ejs.delimiter = ':::'
137-
ejs.openDelimiter = '#'
138-
ejs.closeDelimiter = '#'

src/templates/template-text-classification/main.py

+9-18
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,19 @@
11
import os
22
from pprint import pformat
33
from shutil import copy
4-
from typing import Any, cast
4+
from typing import Any
55

66
import ignite.distributed as idist
77
from data import setup_data
88
from ignite.engine import Events
9-
from ignite.handlers import LRScheduler, PiecewiseLinear
9+
from ignite.handlers import PiecewiseLinear
1010
from ignite.metrics import Accuracy, Loss
1111
from ignite.utils import manual_seed
1212
from models import TransformerModel
1313
from torch import nn, optim
1414
from trainers import setup_evaluator, setup_trainer
1515
from utils import *
1616

17-
try:
18-
from torch.optim.lr_scheduler import _LRScheduler as PyTorchLRScheduler
19-
except ImportError:
20-
from torch.optim.lr_scheduler import LRScheduler as PyTorchLRScheduler
21-
2217
os.environ["TOKENIZERS_PARALLELISM"] = "false" # remove tokenizer paralleism warning
2318

2419

@@ -83,18 +78,11 @@ def run(local_rank: int, config: Any):
8378
logger.info("Configuration: \n%s", pformat(vars(config)))
8479
trainer.logger = evaluator.logger = logger
8580

86-
if isinstance(lr_scheduler, PyTorchLRScheduler):
87-
trainer.add_event_handler(
88-
Events.ITERATION_COMPLETED,
89-
lambda engine: cast(PyTorchLRScheduler, lr_scheduler).step(),
90-
)
91-
elif isinstance(lr_scheduler, LRScheduler):
92-
trainer.add_event_handler(Events.ITERATION_COMPLETED, lr_scheduler)
93-
else:
94-
trainer.add_event_handler(Events.ITERATION_STARTED, lr_scheduler)
81+
trainer.add_event_handler(Events.ITERATION_COMPLETED, lr_scheduler)
9582

96-
# setup ignite handlers
9783
#::: if (it.save_training || it.save_evaluation) { :::#
84+
85+
# setup ignite handlers
9886
#::: if (it.save_training) { :::#
9987
to_save_train = {
10088
"model": model,
@@ -118,6 +106,7 @@ def run(local_rank: int, config: Any):
118106
#::: } :::#
119107

120108
#::: if (it.logger) { :::#
109+
121110
# experiment tracking
122111
if rank == 0:
123112
exp_logger = setup_exp_logging(config, trainer, optimizer, evaluator)
@@ -155,12 +144,14 @@ def _():
155144
)
156145

157146
#::: if (it.logger) { :::#
147+
158148
# close logger
159149
if rank == 0:
160150
exp_logger.close()
161151
#::: } :::#
162-
#
152+
163153
#::: if (it.save_training || it.save_evaluation) { :::#
154+
164155
# show last checkpoint names
165156
logger.info(
166157
"Last training checkpoint name - %s",

src/templates/template-text-classification/trainers.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,11 @@ def train_function(engine: Union[Engine, DeterministicEngine], batch: Any):
4747
engine.state.metrics = metric
4848
return metric
4949

50-
#
5150
#::: if(it.deterministic) { :::#
51+
5252
trainer = DeterministicEngine(train_function)
5353
#::: } else { :::#
54+
5455
trainer = Engine(train_function)
5556
#::: } :::#
5657

src/templates/template-vision-classification/main.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,9 @@ def run(local_rank: int, config: Any):
6666

6767
trainer.add_event_handler(Events.ITERATION_COMPLETED, lr_scheduler)
6868

69-
# setup ignite handlers
7069
#::: if (it.save_training || it.save_evaluation) { :::#
70+
71+
# setup ignite handlers
7172
#::: if (it.save_training) { :::#
7273
to_save_train = {
7374
"model": model,
@@ -91,6 +92,7 @@ def run(local_rank: int, config: Any):
9192
#::: } :::#
9293

9394
#::: if (it.logger) { :::#
95+
9496
# experiment tracking
9597
if rank == 0:
9698
exp_logger = setup_exp_logging(config, trainer, optimizer, evaluator)
@@ -128,12 +130,14 @@ def _():
128130
)
129131

130132
#::: if (it.logger) { :::#
133+
131134
# close logger
132135
if rank == 0:
133136
exp_logger.close()
134137
#::: } :::#
135-
#
138+
136139
#::: if (it.save_training || it.save_evaluation) { :::#
140+
137141
# show last checkpoint names
138142
logger.info(
139143
"Last training checkpoint name - %s",

src/templates/template-vision-classification/trainers.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,11 @@ def train_function(engine: Union[Engine, DeterministicEngine], batch: Any):
3838
}
3939
return {"train_loss": train_loss}
4040

41-
#
4241
#::: if(it.deterministic) { :::#
42+
4343
trainer = DeterministicEngine(train_function)
4444
#::: } else { :::#
45+
4546
trainer = Engine(train_function)
4647
#::: } :::#
4748

src/templates/template-vision-dcgan/main.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,9 @@ def run(local_rank: int, config: Any):
8181
logger.info("Configuration: \n%s", pformat(vars(config)))
8282
trainer.logger = evaluator.logger = logger
8383

84-
# setup ignite handlers
8584
#::: if (it.save_training || it.save_evaluation) { :::#
85+
86+
# setup ignite handlers
8687
#::: if (it.save_training) { :::#
8788
to_save_train = {
8889
"model_d": model_d,
@@ -107,6 +108,7 @@ def run(local_rank: int, config: Any):
107108
#::: } :::#
108109

109110
#::: if (it.logger) { :::#
111+
110112
# experiment tracking
111113
if rank == 0:
112114
exp_logger = setup_exp_logging(
@@ -163,12 +165,14 @@ def _():
163165
)
164166

165167
#::: if (it.logger) { :::#
168+
166169
# close logger
167170
if rank == 0:
168171
exp_logger.close()
169172
#::: } :::#
170-
#
173+
171174
#::: if (it.save_training || it.save_evaluation) { :::#
175+
172176
# show last checkpoint names
173177
logger.info(
174178
"Last training checkpoint name - %s",

src/templates/template-vision-dcgan/trainers.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,11 @@ def train_function(engine: Union[Engine, DeterministicEngine], batch: Any):
8787

8888
return metrics
8989

90-
#
9190
#::: if(it.deterministic) { :::#
91+
9292
trainer = DeterministicEngine(train_function)
9393
#::: } else { :::#
94+
9495
trainer = Engine(train_function)
9596
#::: } :::#
9697

0 commit comments

Comments
 (0)