-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.py
More file actions
198 lines (178 loc) · 7.83 KB
/
db.py
File metadata and controls
198 lines (178 loc) · 7.83 KB
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
# SPDX-License-Identifier: AGPL-3.0-only
# ChatGPT Browser - https://github.com/actuallyrizzn/chatGPT-browser
# Copyright (C) 2024-2025. Licensed under the GNU AGPLv3. See LICENSE.
"""Database access: connection lifecycle, schema init, settings, and conversation import."""
import json
import os
import sqlite3
import sys
from flask import g
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATABASE_PATH = os.environ.get('DATABASE_PATH') or os.path.join(BASE_DIR, 'chatgpt.db')
IMPORT_BATCH_SIZE = 50
def get_db():
try:
if 'db' not in g:
conn = sqlite3.connect(DATABASE_PATH)
conn.execute('PRAGMA foreign_keys = ON')
conn.row_factory = sqlite3.Row
g.db = conn
return g.db
except RuntimeError:
conn = sqlite3.connect(DATABASE_PATH)
conn.execute('PRAGMA foreign_keys = ON')
conn.row_factory = sqlite3.Row
return conn
def close_db(exc):
db = g.pop('db', None)
if db is not None:
db.close()
def _close_if_not_from_g(conn):
try:
if g.get('db') is not conn:
conn.close()
except RuntimeError:
conn.close()
def init_db():
"""Create schema and defaults. Uses schema.sql. Uses get_db() so tests can patch it; run within app.app_context() when calling from CLI."""
conn = get_db()
schema_path = os.path.join(BASE_DIR, 'schema.sql')
with open(schema_path, encoding='utf-8') as f:
conn.executescript(f.read())
conn.commit()
def get_setting(key, default=None):
"""Return setting value; use request-scoped cache in g to batch reads (#30)."""
try:
if 'db' in g:
if '_settings_cache' not in g:
conn = get_db()
rows = conn.execute('SELECT key, value FROM settings').fetchall()
g._settings_cache = {r['key']: r['value'] for r in rows}
return g._settings_cache.get(key, default)
except RuntimeError:
pass
conn = get_db()
try:
setting = conn.execute('SELECT value FROM settings WHERE key = ?', (key,)).fetchone()
return setting['value'] if setting else default
finally:
_close_if_not_from_g(conn)
def set_setting(key, value):
conn = get_db()
try:
conn.execute('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)', (key, value))
conn.commit()
try:
if 'db' in g and '_settings_cache' in g:
g._settings_cache[key] = value
except RuntimeError:
pass
finally:
_close_if_not_from_g(conn)
def _parse_timestamp(ts):
if ts is None:
return None
try:
if isinstance(ts, str):
return float(ts)
return ts
except (ValueError, TypeError):
return None
def import_conversations_data(data):
"""Import a list of conversation dicts into the database. Used by both web upload and CLI ingest."""
if not isinstance(data, list):
data = [data]
total = len(data)
print(f"Importing {total} conversations...")
conn = get_db()
imported = 0
for conversation in data:
try:
conversation_id = conversation.get('id')
if not conversation_id:
print("Skipping conversation: missing ID")
continue
create_time = conversation.get('create_time', '')
update_time = conversation.get('update_time', '')
title = conversation.get('title', '')
conn.execute('''
INSERT OR REPLACE INTO conversations
(id, create_time, update_time, title)
VALUES (?, ?, ?, ?)
''', (conversation_id, create_time, update_time, title))
messages = conversation.get('mapping', {})
inserted_message_ids = set()
# Pass 1: insert all messages so every id exists before we add message_children
# (message_children FK requires both parent_id and child_id to exist in messages)
for message_id, message_data in messages.items():
try:
message = message_data.get('message', {})
if not message:
continue
author = message.get('author', {})
content = message.get('content', {})
role = author.get('role', '')
content_text = json.dumps(content.get('parts', []))
msg_create_time = _parse_timestamp(message.get('create_time'))
msg_update_time = _parse_timestamp(message.get('update_time'))
parent_id = message_data.get('parent', '')
conn.execute('''
INSERT OR REPLACE INTO messages
(id, conversation_id, role, content, create_time, update_time, parent_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (message_id, conversation_id, role, content_text,
msg_create_time, msg_update_time, parent_id))
inserted_message_ids.add(message_id)
metadata = message.get('metadata', {})
if metadata:
conn.execute('''
INSERT OR REPLACE INTO message_metadata
(message_id, message_type, model_slug, citations,
content_references, finish_details, is_complete,
request_id, timestamp_, message_source, serialization_metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
message_id,
metadata.get('message_type', ''),
metadata.get('model_slug', ''),
json.dumps(metadata.get('citations', [])),
json.dumps(metadata.get('content_references', [])),
json.dumps(metadata.get('finish_details', {})),
metadata.get('is_complete', False),
metadata.get('request_id', ''),
metadata.get('timestamp', ''),
metadata.get('message_source', ''),
json.dumps(metadata.get('serialization_metadata', {}))
))
except Exception as e:
print(f"Error processing message {message_id}: {str(e)}")
continue
# Pass 2: insert message_children only where both parent and child were inserted
for message_id, message_data in messages.items():
if message_id not in inserted_message_ids:
continue
try:
children = message_data.get('children', [])
if not children:
continue
conn.execute('DELETE FROM message_children WHERE parent_id = ?', (message_id,))
for child_id in children:
if child_id not in inserted_message_ids:
continue
conn.execute('''
INSERT INTO message_children (parent_id, child_id)
VALUES (?, ?)
''', (message_id, child_id))
except Exception as e:
print(f"Error processing message_children for {message_id}: {str(e)}")
continue
imported += 1
if imported % IMPORT_BATCH_SIZE == 0:
conn.commit()
print(f"Imported {imported} / {total} conversations", file=sys.stderr)
except Exception as e:
print(f"Error processing conversation {conversation_id}: {str(e)}")
continue
conn.commit()
_close_if_not_from_g(conn)
return imported