Spaces:
Runtime error
Runtime error
Delete App_Function_Libraries/Obsidian-Importer.py
Browse files
App_Function_Libraries/Obsidian-Importer.py
DELETED
@@ -1,210 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import re
|
3 |
-
import yaml
|
4 |
-
import sqlite3
|
5 |
-
import traceback
|
6 |
-
import time
|
7 |
-
import zipfile
|
8 |
-
import tempfile
|
9 |
-
import shutil
|
10 |
-
import gradio as gr
|
11 |
-
import logging
|
12 |
-
|
13 |
-
# Set up logging
|
14 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
15 |
-
logger = logging.getLogger(__name__)
|
16 |
-
|
17 |
-
# Assume db connection is set up elsewhere
|
18 |
-
db = None # Replace with your actual database connection
|
19 |
-
|
20 |
-
|
21 |
-
class DatabaseError(Exception):
|
22 |
-
pass
|
23 |
-
|
24 |
-
|
25 |
-
def scan_obsidian_vault(vault_path):
|
26 |
-
markdown_files = []
|
27 |
-
for root, dirs, files in os.walk(vault_path):
|
28 |
-
for file in files:
|
29 |
-
if file.endswith('.md'):
|
30 |
-
markdown_files.append(os.path.join(root, file))
|
31 |
-
return markdown_files
|
32 |
-
|
33 |
-
|
34 |
-
def parse_obsidian_note(file_path):
|
35 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
36 |
-
content = file.read()
|
37 |
-
|
38 |
-
frontmatter = {}
|
39 |
-
frontmatter_match = re.match(r'^---\s*\n(.*?)\n---\s*\n', content, re.DOTALL)
|
40 |
-
if frontmatter_match:
|
41 |
-
frontmatter_text = frontmatter_match.group(1)
|
42 |
-
frontmatter = yaml.safe_load(frontmatter_text)
|
43 |
-
content = content[frontmatter_match.end():]
|
44 |
-
|
45 |
-
tags = re.findall(r'#(\w+)', content)
|
46 |
-
links = re.findall(r'\[\[(.*?)\]\]', content)
|
47 |
-
|
48 |
-
return {
|
49 |
-
'title': os.path.basename(file_path).replace('.md', ''),
|
50 |
-
'content': content,
|
51 |
-
'frontmatter': frontmatter,
|
52 |
-
'tags': tags,
|
53 |
-
'links': links,
|
54 |
-
'file_path': file_path # Add this line
|
55 |
-
}
|
56 |
-
|
57 |
-
|
58 |
-
def import_obsidian_note_to_db(note_data):
|
59 |
-
try:
|
60 |
-
with db.get_connection() as conn:
|
61 |
-
cursor = conn.cursor()
|
62 |
-
|
63 |
-
cursor.execute("SELECT id FROM Media WHERE title = ? AND type = 'obsidian_note'", (note_data['title'],))
|
64 |
-
existing_note = cursor.fetchone()
|
65 |
-
|
66 |
-
if existing_note:
|
67 |
-
media_id = existing_note[0]
|
68 |
-
cursor.execute("""
|
69 |
-
UPDATE Media
|
70 |
-
SET content = ?, author = ?, ingestion_date = CURRENT_TIMESTAMP
|
71 |
-
WHERE id = ?
|
72 |
-
""", (note_data['content'], note_data['frontmatter'].get('author', 'Unknown'), media_id))
|
73 |
-
|
74 |
-
cursor.execute("DELETE FROM MediaKeywords WHERE media_id = ?", (media_id,))
|
75 |
-
else:
|
76 |
-
cursor.execute("""
|
77 |
-
INSERT INTO Media (title, content, type, author, ingestion_date, url)
|
78 |
-
VALUES (?, ?, 'obsidian_note', ?, CURRENT_TIMESTAMP, ?)
|
79 |
-
""", (note_data['title'], note_data['content'], note_data['frontmatter'].get('author', 'Unknown'),
|
80 |
-
note_data['file_path']))
|
81 |
-
|
82 |
-
media_id = cursor.lastrowid
|
83 |
-
|
84 |
-
for tag in note_data['tags']:
|
85 |
-
cursor.execute("INSERT OR IGNORE INTO Keywords (keyword) VALUES (?)", (tag,))
|
86 |
-
cursor.execute("SELECT id FROM Keywords WHERE keyword = ?", (tag,))
|
87 |
-
keyword_id = cursor.fetchone()[0]
|
88 |
-
cursor.execute("INSERT OR IGNORE INTO MediaKeywords (media_id, keyword_id) VALUES (?, ?)",
|
89 |
-
(media_id, keyword_id))
|
90 |
-
|
91 |
-
frontmatter_str = yaml.dump(note_data['frontmatter'])
|
92 |
-
cursor.execute("""
|
93 |
-
INSERT INTO MediaModifications (media_id, prompt, summary, modification_date)
|
94 |
-
VALUES (?, 'Obsidian Frontmatter', ?, CURRENT_TIMESTAMP)
|
95 |
-
""", (media_id, frontmatter_str))
|
96 |
-
|
97 |
-
# Update full-text search index
|
98 |
-
cursor.execute('INSERT OR REPLACE INTO media_fts (rowid, title, content) VALUES (?, ?, ?)',
|
99 |
-
(media_id, note_data['title'], note_data['content']))
|
100 |
-
|
101 |
-
action = "Updated" if existing_note else "Imported"
|
102 |
-
logger.info(f"{action} Obsidian note: {note_data['title']}")
|
103 |
-
return True, None
|
104 |
-
except sqlite3.Error as e:
|
105 |
-
error_msg = f"Database error {'updating' if existing_note else 'importing'} note {note_data['title']}: {str(e)}"
|
106 |
-
logger.error(error_msg)
|
107 |
-
return False, error_msg
|
108 |
-
except Exception as e:
|
109 |
-
error_msg = f"Unexpected error {'updating' if existing_note else 'importing'} note {note_data['title']}: {str(e)}\n{traceback.format_exc()}"
|
110 |
-
logger.error(error_msg)
|
111 |
-
return False, error_msg
|
112 |
-
|
113 |
-
|
114 |
-
def import_obsidian_vault(vault_path, progress=gr.Progress()):
|
115 |
-
try:
|
116 |
-
markdown_files = scan_obsidian_vault(vault_path)
|
117 |
-
total_files = len(markdown_files)
|
118 |
-
imported_files = 0
|
119 |
-
errors = []
|
120 |
-
|
121 |
-
for i, file_path in enumerate(markdown_files):
|
122 |
-
try:
|
123 |
-
note_data = parse_obsidian_note(file_path)
|
124 |
-
success, error_msg = import_obsidian_note_to_db(note_data)
|
125 |
-
if success:
|
126 |
-
imported_files += 1
|
127 |
-
else:
|
128 |
-
errors.append(error_msg)
|
129 |
-
except Exception as e:
|
130 |
-
error_msg = f"Error processing {file_path}: {str(e)}"
|
131 |
-
logger.error(error_msg)
|
132 |
-
errors.append(error_msg)
|
133 |
-
|
134 |
-
progress((i + 1) / total_files, f"Imported {imported_files} of {total_files} files")
|
135 |
-
time.sleep(0.1) # Small delay to prevent UI freezing
|
136 |
-
|
137 |
-
return imported_files, total_files, errors
|
138 |
-
except Exception as e:
|
139 |
-
error_msg = f"Error scanning vault: {str(e)}\n{traceback.format_exc()}"
|
140 |
-
logger.error(error_msg)
|
141 |
-
return 0, 0, [error_msg]
|
142 |
-
|
143 |
-
|
144 |
-
def process_obsidian_zip(zip_file):
|
145 |
-
with tempfile.TemporaryDirectory() as temp_dir:
|
146 |
-
try:
|
147 |
-
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
|
148 |
-
zip_ref.extractall(temp_dir)
|
149 |
-
|
150 |
-
imported_files, total_files, errors = import_obsidian_vault(temp_dir)
|
151 |
-
|
152 |
-
return imported_files, total_files, errors
|
153 |
-
except zipfile.BadZipFile:
|
154 |
-
error_msg = "The uploaded file is not a valid zip file."
|
155 |
-
logger.error(error_msg)
|
156 |
-
return 0, 0, [error_msg]
|
157 |
-
except Exception as e:
|
158 |
-
error_msg = f"Error processing zip file: {str(e)}\n{traceback.format_exc()}"
|
159 |
-
logger.error(error_msg)
|
160 |
-
return 0, 0, [error_msg]
|
161 |
-
finally:
|
162 |
-
shutil.rmtree(temp_dir, ignore_errors=True)
|
163 |
-
|
164 |
-
|
165 |
-
# Gradio interface
|
166 |
-
with gr.Blocks() as demo:
|
167 |
-
gr.Markdown("# Content Export and Import Interface")
|
168 |
-
|
169 |
-
# ... (your existing tabs and components)
|
170 |
-
|
171 |
-
with gr.Tab("Import Obsidian Vault"):
|
172 |
-
gr.Markdown("## Import Obsidian Vault")
|
173 |
-
with gr.Row():
|
174 |
-
vault_path_input = gr.Textbox(label="Obsidian Vault Path (Local)")
|
175 |
-
vault_zip_input = gr.File(label="Upload Obsidian Vault (Zip)")
|
176 |
-
import_vault_button = gr.Button("Import Obsidian Vault")
|
177 |
-
import_status = gr.Textbox(label="Import Status", interactive=False)
|
178 |
-
|
179 |
-
|
180 |
-
def import_vault(vault_path, vault_zip):
|
181 |
-
if vault_zip:
|
182 |
-
imported, total, errors = process_obsidian_zip(vault_zip.name)
|
183 |
-
elif vault_path:
|
184 |
-
imported, total, errors = import_obsidian_vault(vault_path)
|
185 |
-
else:
|
186 |
-
return "Please provide either a local vault path or upload a zip file."
|
187 |
-
|
188 |
-
status = f"Imported {imported} out of {total} files.\n"
|
189 |
-
if errors:
|
190 |
-
status += f"Encountered {len(errors)} errors:\n" + "\n".join(errors)
|
191 |
-
return status
|
192 |
-
|
193 |
-
|
194 |
-
import_vault_button.click(
|
195 |
-
fn=import_vault,
|
196 |
-
inputs=[vault_path_input, vault_zip_input],
|
197 |
-
outputs=[import_status],
|
198 |
-
show_progress=True
|
199 |
-
)
|
200 |
-
|
201 |
-
# ... (rest of your existing code)
|
202 |
-
|
203 |
-
demo.launch()
|
204 |
-
|
205 |
-
# This comprehensive solution includes:
|
206 |
-
#
|
207 |
-
# Enhanced error handling throughout the import process.
|
208 |
-
# Progress updates for large vaults using Gradio's progress bar.
|
209 |
-
# The ability to update existing notes if they're reimported.
|
210 |
-
# Support for importing Obsidian vaults from both local directories and uploaded zip files.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|