Skip to content

Commit c76f3d3

Browse files
committed
frontend
1 parent 646eca3 commit c76f3d3

File tree

7 files changed

+452
-5852
lines changed

7 files changed

+452
-5852
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.env

.i

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
env
Binary file not shown.

app.py

Lines changed: 64 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@
1313
import asyncio
1414
import aiohttp
1515
from queue import Queue
16-
import psycopg2
17-
from psycopg2.extras import execute_values
16+
import sqlite3
1817
from datetime import datetime
1918

2019
load_dotenv() # Load environment variables from .env file
@@ -27,24 +26,16 @@
2726
if not OPENAI_API_KEY:
2827
raise ValueError("No OpenAI API key found. Please set the OPENAI_API_KEY environment variable.")
2928

30-
# Initialize PostgreSQL database
29+
# Initialize SQLite database
3130
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')
3832
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)''')
4839
conn.commit()
4940
conn.close()
5041

@@ -181,36 +172,60 @@ def generate():
181172

182173
return Response(generate(), mimetype='text/event-stream')
183174

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+
184206
@app.route('/save-pdf', methods=['POST'])
185207
def save_pdf():
186208
try:
187209
content = request.json['content']
188210
title = request.json['title']
189211
language = request.json['language']
190212
ip = request.remote_addr
191-
timestamp = datetime.now()
213+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
192214

193215
pdf_buffer = create_pdf(content, title, language)
194216

195217
# Save PDF to file
196-
filename = f"{ip}_{timestamp.strftime('%Y%m%d_%H%M%S')}.pdf"
218+
filename = f"{ip}_{timestamp}.pdf"
197219
filepath = os.path.join('saved_pdfs', filename)
198220
os.makedirs('saved_pdfs', exist_ok=True)
199221
with open(filepath, 'wb') as f:
200222
f.write(pdf_buffer.getvalue())
201223

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')
209226
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))
214229
conn.commit()
215230
conn.close()
216231

@@ -220,18 +235,28 @@ def save_pdf():
220235
app.logger.error(traceback.format_exc())
221236
return jsonify({'error': str(e)}), 500
222237

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+
223253
@app.route('/download-saved-pdf/<int:pdf_id>', methods=['GET'])
224254
def download_saved_pdf(pdf_id):
225255
try:
226256
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')
233258
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))
235260
result = c.fetchone()
236261
conn.close()
237262

@@ -246,4 +271,4 @@ def download_saved_pdf(pdf_id):
246271
return jsonify({'error': str(e)}), 500
247272

248273
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)

pdfs.db

12 KB
Binary file not shown.

0 commit comments

Comments
 (0)