-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
207 lines (156 loc) · 7.2 KB
/
script.py
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
import json
import os
import yaml
from datetime import datetime
# Load the configuration from config.yaml
with open('config.yaml', 'r') as config_file:
config = yaml.safe_load(config_file)
# Extract configuration details
json_file = config['json_file']
output_dir = config['output_dir']
properties = config['properties']
# Create the output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Function to sanitize file names
def sanitize_filename(name):
return "".join(c for c in name if c.isalnum() or c in " ._-").rstrip()
# Function to format date
def format_date(date_str):
try:
date_obj = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
return date_obj.strftime("%Y-%m-%d")
except ValueError:
return date_str
# Function to generate daily note link based on a date string
def generate_daily_note_link(date_str):
date_obj = datetime.strptime(date_str, '%Y-%m-%d')
# date_obj = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')
year = date_obj.strftime('%Y')
month_num = date_obj.strftime('%m')
month_name = date_obj.strftime('%B')
day_date = date_obj.strftime('%Y-%m-%d')
day_name = date_obj.strftime('%A')
return f"/DailyNotes/{year}/{month_num}-{month_name}/{day_date}-{day_name}.md"
# Function to properly capitalise strings
def format_string(s):
return ' '.join(word.capitalize() for word in s.split('_'))
# Function to convery bool to symbols
def format_bool(value):
return '✓' if value else '✗'
# Function to create markdown content for a bean
def create_markdown(bean):
content = []
yaml_frontmatter = []
# Process each property based on the configuration
if properties.get('name', False):
name = bean.get('name', 'Unnamed Bean')
yaml_frontmatter.append(f'name: "{name}"')
content.append(f"# {name}")
if properties.get('roaster', False):
roaster = bean.get('roaster', 'Unknown Roaster')
yaml_frontmatter.append(f'roaster: "{roaster}"')
content.append(f"**Roaster:** {roaster}")
if properties.get('roasting_date', False):
roasting_date = format_date(bean.get('roastingDate', ''))
if roasting_date != '':
yaml_frontmatter.append(f'roasting_date: "{roasting_date}"')
daily_note_link = generate_daily_note_link(roasting_date)
content.append(
f"**Roasting Date:** [{roasting_date}]({daily_note_link})")
if properties.get('open_date', False):
open_date = format_date(bean.get('openDate', ''))
if open_date != '':
yaml_frontmatter.append(f'open_date: "{open_date}"')
daily_note_link = generate_daily_note_link(open_date)
content.append(
f"**Opening Date:** [{open_date}]({daily_note_link})")
if properties.get('note', False):
note = bean.get('note', 'No Notes')
content.append(f"## Notes\n{note}")
if properties.get('aromatics', False):
aromatics = bean.get('aromatics', 'No Aromatics Info')
content.append(f"**Aromatics:** {aromatics}")
if properties.get('weight', False):
weight = bean.get('weight', 'Unknown Weight')
yaml_frontmatter.append(f'weight: {weight}g')
content.append(f"**Weight:** {weight}g")
if properties.get('cost', False):
cost = bean.get('cost', 'Unknown Cost')
yaml_frontmatter.append(f'cost: ₹{cost}')
content.append(f"**Cost:** ₹{cost}")
if properties.get('rating', False):
rating = bean.get('rating', 'No Rating')
yaml_frontmatter.append(f'rating: {rating}/5')
content.append(f"**Rating:** {rating}/5")
if properties.get('favourite', False):
favourite = bean.get('favourite', False)
yaml_frontmatter.append(f'favourite: {favourite}')
content.append(f"**Favourite:** {format_bool(favourite)}")
if properties.get('finished', False):
finished = bean.get('finished', False)
yaml_frontmatter.append(f'finished: {finished}')
content.append(f"**Finished:** {format_bool(finished)}")
if properties.get('decaffeinated', False):
decaffeinated = bean.get('decaffeinated', False)
yaml_frontmatter.append(f'decaffeinated: {decaffeinated}')
content.append(f"**Decaffeinated:** {format_bool(decaffeinated)}")
if properties.get('roast', False):
roast = format_string(bean.get('roast', 'Unknown'))
yaml_frontmatter.append(f'roast: "{roast}"')
content.append(f"**Roast Level:** {roast}")
if properties.get('roast_range', False):
roast_range = bean.get('roast_range', 0)
yaml_frontmatter.append(f'roast_range: {roast_range}')
content.append(f"**Roast Range:** {roast_range}")
if properties.get('bean_mix', False):
bean_mix = format_string(bean.get('beanMix', 'Unknown'))
yaml_frontmatter.append(f'bean_mix: "{bean_mix}"')
content.append(f"**Bean Mix:** {bean_mix}")
if properties.get('attachments', False):
attachments = bean.get('attachments', [])
if attachments:
image_path = f"photos/beans/{os.path.basename(attachments[0])}"
yaml_frontmatter.append(f'poster: "[[{image_path}]]"')
content.append(f"![Bean Image]({image_path})\n\n")
content.append("**Repeat purchases**\n\n")
content.append("| Roasting Date | Weight| Cost|\n|---|---:|---:|\n")
# Combine YAML frontmatter and content
yaml_section = "---\n" + \
"\n".join(yaml_frontmatter) + "\ntags:\n - Coffee/Bean\n---\n\n"
markdown_content = yaml_section + "\n".join(content)
return markdown_content
def amend_markdown(makrown_file, bean):
roasting_date = format_date(bean.get('roastingDate', ''))
daily_note_link = generate_daily_note_link(roasting_date)
weight = bean.get('weight', 0)
cost = bean.get('cost', 0)
with open(makrown_file, 'r', encoding='utf-8') as file:
lines = file.readlines()
for i, line in enumerate(lines):
if line.startswith("roasting_date:"):
lines[i] = f'roasting_date: "{roasting_date}"\n'
elif line.startswith("weight:"):
lines[i] = f'weight: {weight}g\n'
elif line.startswith("cost:"):
lines[i] = f'cost: ₹{cost}\n'
lines.append(f"| [{roasting_date}]({daily_note_link}) | {
weight}g | ₹{cost}|\n")
markdown_content = ''.join(lines)
return markdown_content
# Read the JSON file
with open(json_file, 'r', encoding='utf-8') as file:
data = json.load(file)
# Process each bean and create a markdown file
for bean in data.get('BEANS', []):
print(f"Processing {bean.get('name', 'Unnamed Bean')}...")
bean_name = sanitize_filename(bean.get('name', 'Unnamed Bean'))
markdown_file = os.path.join(output_dir, f"{bean_name}.md")
if os.path.exists(markdown_file):
print(f"Appending history to {bean_name}.md...")
markdown_content = amend_markdown(markdown_file, bean)
else:
print(f"Creating {bean_name}.md...")
markdown_content = create_markdown(bean)
with open(markdown_file, 'w', encoding='utf-8') as md_file:
md_file.write(markdown_content)
print(f"Markdown files created in '{output_dir}' directory.")