13
13
import asyncio
14
14
import aiohttp
15
15
from queue import Queue
16
- import psycopg2
17
- from psycopg2 .extras import execute_values
16
+ import sqlite3
18
17
from datetime import datetime
19
18
20
19
load_dotenv () # Load environment variables from .env file
27
26
if not OPENAI_API_KEY :
28
27
raise ValueError ("No OpenAI API key found. Please set the OPENAI_API_KEY environment variable." )
29
28
30
- # Initialize PostgreSQL database
29
+ # Initialize SQLite database
31
30
def init_db ():
32
- conn = psycopg2 .connect (
33
- host = os .getenv ("DB_HOST" ),
34
- database = os .getenv ("DB_NAME" ),
35
- user = os .getenv ("DB_USER" ),
36
- password = os .getenv ("DB_PASSWORD" )
37
- )
31
+ conn = sqlite3 .connect ('pdfs.db' )
38
32
c = conn .cursor ()
39
- c .execute ('''
40
- CREATE TABLE IF NOT EXISTS pdfs (
41
- id SERIAL PRIMARY KEY,
42
- ip TEXT,
43
- title TEXT,
44
- filepath TEXT,
45
- timestamp TIMESTAMP
46
- )
47
- ''' )
33
+ c .execute ('''CREATE TABLE IF NOT EXISTS pdfs
34
+ (id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ ip TEXT,
36
+ title TEXT,
37
+ filepath TEXT,
38
+ timestamp TEXT)''' )
48
39
conn .commit ()
49
40
conn .close ()
50
41
@@ -181,36 +172,60 @@ def generate():
181
172
182
173
return Response (generate (), mimetype = 'text/event-stream' )
183
174
175
+ @app .route ('/download-pdf' , methods = ['POST' ])
176
+ def download_pdf ():
177
+ try :
178
+ content = request .json ['content' ]
179
+ title = request .json ['title' ]
180
+ language = request .json ['language' ]
181
+ pdf_buffer = create_pdf (content , title , language )
182
+
183
+ # Save the PDF
184
+ ip = request .remote_addr
185
+ timestamp = datetime .now ().strftime ("%Y%m%d_%H%M%S" )
186
+ filename = f"{ ip } _{ timestamp } .pdf"
187
+ filepath = os .path .join ('saved_pdfs' , filename )
188
+ os .makedirs ('saved_pdfs' , exist_ok = True )
189
+ with open (filepath , 'wb' ) as f :
190
+ f .write (pdf_buffer .getvalue ())
191
+
192
+ # Save metadata to database
193
+ conn = sqlite3 .connect ('pdfs.db' )
194
+ c = conn .cursor ()
195
+ c .execute ("INSERT INTO pdfs (ip, title, filepath, timestamp) VALUES (?, ?, ?, ?)" ,
196
+ (ip , title , filepath , timestamp ))
197
+ conn .commit ()
198
+ conn .close ()
199
+
200
+ return send_file (io .BytesIO (pdf_buffer .getvalue ()), download_name = f"{ title } .pdf" , as_attachment = True , mimetype = 'application/pdf' )
201
+ except Exception as e :
202
+ app .logger .error (f"PDF download error: { str (e )} " )
203
+ app .logger .error (traceback .format_exc ())
204
+ return jsonify ({'error' : str (e )}), 500
205
+
184
206
@app .route ('/save-pdf' , methods = ['POST' ])
185
207
def save_pdf ():
186
208
try :
187
209
content = request .json ['content' ]
188
210
title = request .json ['title' ]
189
211
language = request .json ['language' ]
190
212
ip = request .remote_addr
191
- timestamp = datetime .now ()
213
+ timestamp = datetime .now (). strftime ( "%Y%m%d_%H%M%S" )
192
214
193
215
pdf_buffer = create_pdf (content , title , language )
194
216
195
217
# Save PDF to file
196
- filename = f"{ ip } _{ timestamp . strftime ( '%Y%m%d_%H%M%S' ) } .pdf"
218
+ filename = f"{ ip } _{ timestamp } .pdf"
197
219
filepath = os .path .join ('saved_pdfs' , filename )
198
220
os .makedirs ('saved_pdfs' , exist_ok = True )
199
221
with open (filepath , 'wb' ) as f :
200
222
f .write (pdf_buffer .getvalue ())
201
223
202
- # Save metadata to PostgreSQL database
203
- conn = psycopg2 .connect (
204
- host = os .getenv ("DB_HOST" ),
205
- database = os .getenv ("DB_NAME" ),
206
- user = os .getenv ("DB_USER" ),
207
- password = os .getenv ("DB_PASSWORD" )
208
- )
224
+ # Save metadata to database
225
+ conn = sqlite3 .connect ('pdfs.db' )
209
226
c = conn .cursor ()
210
- c .execute (
211
- "INSERT INTO pdfs (ip, title, filepath, timestamp) VALUES (%s, %s, %s, %s)" ,
212
- (ip , title , filepath , timestamp )
213
- )
227
+ c .execute ("INSERT INTO pdfs (ip, title, filepath, timestamp) VALUES (?, ?, ?, ?)" ,
228
+ (ip , title , filepath , timestamp ))
214
229
conn .commit ()
215
230
conn .close ()
216
231
@@ -220,18 +235,28 @@ def save_pdf():
220
235
app .logger .error (traceback .format_exc ())
221
236
return jsonify ({'error' : str (e )}), 500
222
237
238
+ @app .route ('/get-saved-pdfs' , methods = ['GET' ])
239
+ def get_saved_pdfs ():
240
+ try :
241
+ ip = request .remote_addr
242
+ conn = sqlite3 .connect ('pdfs.db' )
243
+ c = conn .cursor ()
244
+ c .execute ("SELECT id, title, timestamp FROM pdfs WHERE ip = ? ORDER BY timestamp DESC" , (ip ,))
245
+ pdfs = [{'id' : row [0 ], 'title' : row [1 ], 'timestamp' : row [2 ]} for row in c .fetchall ()]
246
+ conn .close ()
247
+ return jsonify ({'pdfs' : pdfs })
248
+ except Exception as e :
249
+ app .logger .error (f"Get saved PDFs error: { str (e )} " )
250
+ app .logger .error (traceback .format_exc ())
251
+ return jsonify ({'error' : str (e )}), 500
252
+
223
253
@app .route ('/download-saved-pdf/<int:pdf_id>' , methods = ['GET' ])
224
254
def download_saved_pdf (pdf_id ):
225
255
try :
226
256
ip = request .remote_addr
227
- conn = psycopg2 .connect (
228
- host = os .getenv ("DB_HOST" ),
229
- database = os .getenv ("DB_NAME" ),
230
- user = os .getenv ("DB_USER" ),
231
- password = os .getenv ("DB_PASSWORD" )
232
- )
257
+ conn = sqlite3 .connect ('pdfs.db' )
233
258
c = conn .cursor ()
234
- c .execute ("SELECT filepath, title FROM pdfs WHERE id = %s AND ip = %s " , (pdf_id , ip ))
259
+ c .execute ("SELECT filepath, title FROM pdfs WHERE id = ? AND ip = ? " , (pdf_id , ip ))
235
260
result = c .fetchone ()
236
261
conn .close ()
237
262
@@ -246,4 +271,4 @@ def download_saved_pdf(pdf_id):
246
271
return jsonify ({'error' : str (e )}), 500
247
272
248
273
if __name__ == "__main__" :
249
- app .run (debug = True , host = "0.0.0.0" , port = 5151 )
274
+ app .run (debug = True , host = "0.0.0.0" , port = 5151 )
0 commit comments