cmcmaster commited on
Commit
9ee0be3
·
verified ·
1 Parent(s): e0b6581

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +89 -50
main.py CHANGED
@@ -66,13 +66,17 @@ css = Style("""
66
  margin-top: 20px;
67
  }
68
 
 
 
 
 
69
  .download-link {
70
  display: inline-block;
71
  padding: 10px 20px;
72
  background-color: #2c3e50;
73
  color: white;
74
  border-radius: 3px;
75
- margin: 10px 0;
76
  font-family: Georgia, Times, serif;
77
  }
78
 
@@ -90,75 +94,110 @@ app = FastHTML(hdrs=(css, MarkdownJS(),
90
  # Start the scheduler when the app starts
91
  @app.on_event("startup")
92
  async def start_scheduler():
93
- scheduler.start()
94
 
95
 
96
  # Shut down the scheduler when the app stops
97
  @app.on_event("shutdown")
98
  async def shutdown_scheduler():
99
- scheduler.shutdown()
100
 
101
 
102
  def get_newsletter_list():
103
- # Fetch the list of newsletters from the Hugging Face repository
104
- files = api.list_repo_files(repo_id=DATASET_NAME, repo_type="dataset")
105
- newsletters = [f for f in files if f.endswith('newsletter.json')]
106
- return sorted(newsletters, reverse=True)
107
 
108
 
109
  def get_newsletter_content(path):
110
- # Download and parse the newsletter content
111
- content = api.hf_hub_download(repo_id=DATASET_NAME,
112
  filename=path,
113
  repo_type="dataset")
114
- with open(content, 'r') as f:
115
- return json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
 
118
  @app.get("/")
119
  def index():
120
- newsletters = get_newsletter_list()
121
- links = [
122
- Li(
123
- A(datetime.strptime(n.split('/')[0], '%Y%m%d').strftime('%B %d, %Y'),
124
- href=f"/newsletter/{n.split('/')[0]}")) for n in newsletters
125
- ]
126
- return Titled("This Week in Rheumatology", H2("Available Newsletters"),
127
- Ul(*links))
128
 
129
 
130
  @app.get("/newsletter/{date}")
131
  def newsletter(date: str):
132
- path = f"{date}/newsletter.json"
133
- pdf_path = f"{date}/newsletter.pdf"
134
- try:
135
- content = get_newsletter_content(path)
136
- return Titled(
137
- f"This Week in Rheumatology - {content['date']}",
138
- A("Back to Index", href="/"),
139
- Div(
140
- A("Download PDF", href=f"/download/{date}", cls="download-link")
141
- ),
142
- Div(content['content'], cls="marked"))
143
- except Exception as e:
144
- return Titled("Error", H2("Newsletter not found"),
145
- P(f"Unable to load newsletter for date: {date}"),
146
- A("Back to Index", href="/"))
147
-
148
-
149
- @app.get("/download/{date}")
150
- def download_pdf(date: str):
151
- try:
152
- pdf_path = f"{date}/newsletter.pdf"
153
- content = api.hf_hub_download(repo_id=DATASET_NAME,
154
- filename=pdf_path,
155
- repo_type="dataset")
156
- return FileResponse(content,
157
- media_type="application/pdf",
158
- filename=f"newsletter_{date}.pdf")
159
- except Exception as e:
160
- return Titled("Error", H2("PDF not found"),
161
- P(f"Unable to load PDF for date: {date}"),
162
- A("Back to Index", href="/"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  serve()
 
66
  margin-top: 20px;
67
  }
68
 
69
+ .download-links {
70
+ margin: 20px 0;
71
+ }
72
+
73
  .download-link {
74
  display: inline-block;
75
  padding: 10px 20px;
76
  background-color: #2c3e50;
77
  color: white;
78
  border-radius: 3px;
79
+ margin: 0 10px 10px 0;
80
  font-family: Georgia, Times, serif;
81
  }
82
 
 
94
  # Start the scheduler when the app starts
95
  @app.on_event("startup")
96
  async def start_scheduler():
97
+ scheduler.start()
98
 
99
 
100
  # Shut down the scheduler when the app stops
101
  @app.on_event("shutdown")
102
  async def shutdown_scheduler():
103
+ scheduler.shutdown()
104
 
105
 
106
  def get_newsletter_list():
107
+ # Fetch the list of newsletters from the Hugging Face repository
108
+ files = api.list_repo_files(repo_id=DATASET_NAME, repo_type="dataset")
109
+ newsletters = [f for f in files if f.endswith('newsletter.json')]
110
+ return sorted(newsletters, reverse=True)
111
 
112
 
113
  def get_newsletter_content(path):
114
+ # Download and parse the newsletter content
115
+ content = api.hf_hub_download(repo_id=DATASET_NAME,
116
  filename=path,
117
  repo_type="dataset")
118
+ with open(content, 'r') as f:
119
+ return json.load(f)
120
+
121
+
122
+ def check_format_exists(date: str, format: str) -> bool:
123
+ """Check if a specific format exists for a given date"""
124
+ try:
125
+ api.hf_hub_download(
126
+ repo_id=DATASET_NAME,
127
+ filename=f"{date}/newsletter.{format}",
128
+ repo_type="dataset"
129
+ )
130
+ return True
131
+ except Exception:
132
+ return False
133
 
134
 
135
  @app.get("/")
136
  def index():
137
+ newsletters = get_newsletter_list()
138
+ links = [
139
+ Li(
140
+ A(datetime.strptime(n.split('/')[0], '%Y%m%d').strftime('%B %d, %Y'),
141
+ href=f"/newsletter/{n.split('/')[0]}")) for n in newsletters
142
+ ]
143
+ return Titled("This Week in Rheumatology", H2("Available Newsletters"),
144
+ Ul(*links))
145
 
146
 
147
  @app.get("/newsletter/{date}")
148
  def newsletter(date: str):
149
+ path = f"{date}/newsletter.json"
150
+ try:
151
+ content = get_newsletter_content(path)
152
+
153
+ # Create download links div
154
+ download_links = []
155
+
156
+ # Check for PDF
157
+ if check_format_exists(date, "pdf"):
158
+ download_links.append(
159
+ A("Download PDF", href=f"/download/{date}/pdf", cls="download-link")
160
+ )
161
+
162
+ # Check for EPUB
163
+ if check_format_exists(date, "epub"):
164
+ download_links.append(
165
+ A("Download EPUB", href=f"/download/{date}/epub", cls="download-link")
166
+ )
167
+
168
+ return Titled(
169
+ f"This Week in Rheumatology - {content['date']}",
170
+ A("Back to Index", href="/"),
171
+ Div(*download_links, cls="download-links"),
172
+ Div(content['content'], cls="marked"))
173
+ except Exception as e:
174
+ return Titled("Error", H2("Newsletter not found"),
175
+ P(f"Unable to load newsletter for date: {date}"),
176
+ A("Back to Index", href="/"))
177
+
178
+
179
+ @app.get("/download/{date}/{format}")
180
+ def download_file(date: str, format: str):
181
+ try:
182
+ file_path = f"{date}/newsletter.{format}"
183
+ content = api.hf_hub_download(repo_id=DATASET_NAME,
184
+ filename=file_path,
185
+ repo_type="dataset")
186
+
187
+ # Set appropriate media type and filename
188
+ if format == "pdf":
189
+ media_type = "application/pdf"
190
+ elif format == "epub":
191
+ media_type = "application/epub+zip"
192
+ else:
193
+ raise ValueError(f"Unsupported format: {format}")
194
+
195
+ return FileResponse(content,
196
+ media_type=media_type,
197
+ filename=f"newsletter_{date}.{format}")
198
+ except Exception as e:
199
+ return Titled("Error", H2(f"{format.upper()} not found"),
200
+ P(f"Unable to load {format.upper()} for date: {date}"),
201
+ A("Back to Index", href="/"))
202
 
203
  serve()