File size: 14,143 Bytes
9336543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import streamlit as st
import os
import io
import requests
from lxml import etree
from converter import ModsConverter
from urllib.parse import quote, unquote

st.set_page_config(
    page_title="PubTypeConverter | DORA Tools",
    page_icon="πŸ”„",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# Custom CSS for a modern, premium look
st.markdown("""

<style>

    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');

    

    html, body, [class*="css"] {

        font-family: 'Inter', sans-serif;

    }

    

    .stApp {

        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);

    }

    

    /* Premium Header */

    .title-container {

        padding: 2rem 0;

        text-align: center;

        background: rgba(255, 255, 255, 0.4);

        backdrop-filter: blur(10px);

        border-radius: 20px;

        margin-bottom: 2rem;

        border: 1px solid rgba(255, 255, 255, 0.5);

        box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.07);

    }

    

    .main-title {

        font-size: 3rem;

        font-weight: 700;

        background: linear-gradient(90deg, #1e3a8a, #3b82f6);

        -webkit-background-clip: text;

        -webkit-text-fill-color: transparent;

        margin-bottom: 0.5rem;

    }

    

    .sub-title {

        color: #64748b;

        font-size: 1.1rem;

    }

    

    /* Section Styling */

    .stSelectbox, .stTextInput, .stButton {

        margin-bottom: 1rem;

    }

    

    /* Card-like containers for results */

    .result-card {

        background: white;

        padding: 1.5rem;

        border-radius: 15px;

        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);

        margin-bottom: 1.5rem;

        border-left: 5px solid #3b82f6;

    }

    

    /* Step indicators */

    .step-header {

        font-weight: 600;

        color: #1e293b;

        margin-bottom: 1rem;

        display: flex;

        align-items: center;

        gap: 0.5rem;

    }

    

    .step-number {

        background: #3b82f6;

        color: white;

        width: 24px;

        height: 24px;

        border-radius: 50%;

        display: flex;

        align-items: center;

        justify-content: center;

        font-size: 0.8rem;

    }

</style>



<div class="title-container">

    <div class="main-title">DORA PubTypeConverter</div>

    <div class="sub-title">DORA Publication Type Transformation Helper</div>

</div>

""", unsafe_allow_html=True)

# Setup paths
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
RESOURCE_DIR = os.path.join(BASE_DIR, "PubTypeConverter_resources")
TEMPLATE_DIR = os.path.join(RESOURCE_DIR, "PubTypeConverter_templates")
CONFIG_FILE = os.path.join(RESOURCE_DIR, "PubTypeConverterConfig.xml")

# Initialize Session State
if 'converter' not in st.session_state:
    converter = ModsConverter()
    if os.path.exists(CONFIG_FILE):
        converter.load_config(CONFIG_FILE)
    else:
        st.warning(f"Configuration file not found at {CONFIG_FILE}. Content moving rules will not be applied.")
    st.session_state.converter = converter

if 'loaded_files' not in st.session_state:
    st.session_state.loaded_files = [] # List of dicts: {'name': str, 'content': bytes}

# Load templates
templates = []
if os.path.exists(TEMPLATE_DIR):
    for f in os.listdir(TEMPLATE_DIR):
        if f.lower().endswith(".xml"):
            templates.append(f)
else:
    st.error(f"Template directory not found: {TEMPLATE_DIR}")
templates.sort()


# Helper function to fetch from DORA
def fetch_from_dora(pid_or_url, repo):
    url = pid_or_url.strip()
    
    # Handle double-encoded PIDs (e.g. psi%253A84411 -> psi%3A84411 -> psi:84411)
    # We unquote until the string stabilizes
    prev = None
    while url != prev:
        prev = url
        url = unquote(url)
    fallback_www = None
    fallback_oai = None
    
    if not url.startswith("http"):
        # Construct URL from PID
        # Assume PID format like "psi:12345" or just "12345"
        if ":" in url:
            parts = url.split(":")
            repo_prefix = parts[0].lower()
            # Force prefix to lowercase for repo mapping
            pid_val = f"{repo_prefix}:{parts[1]}"
            repo = repo_prefix 
        else:
             # Use selected repo
             pid_val = f"{repo}:{url}"
        
        # URL Encode the PID part - essential for Islandora
        quoted_pid = quote(pid_val)
        
        # Primary: Admin (Intranet, preferred)
        url = f"https://admin.dora.lib4ri.ch/{repo}/islandora/object/{quoted_pid}/datastream/MODS/view"
        
        # Fallback 1: WWW (Public mirror)
        fallback_www = f"https://www.dora.lib4ri.ch/{repo}/islandora/object/{quoted_pid}/datastream/MODS/view"
        
        # Fallback 2: OAI-PMH (Robust Public Access)
        # Use quoted PID for identifier to be safe (suggested by user example)
        fallback_oai = f"https://www.dora.lib4ri.ch/{repo}/oai2/request?verb=GetRecord&metadataPrefix=mods&identifier={quoted_pid}"

    headers = {'User-Agent': 'curl/7.68.0'}
    
    # helper to check OAI response for valid content
    def check_oai_response(content):
        try:
             root = etree.fromstring(content)
             
             # Check for OAI error code
             if root.xpath(".//*[local-name()='error']"):
                 return False
             
             # Ultimate robust search: find first 'mods' element regardless of namespace/prefix
             mods_nodes = root.xpath(".//*[local-name()='mods']")
             if mods_nodes:
                 return etree.tostring(mods_nodes[0], encoding='utf-8')
        except:
             pass
        return None

    try:
        # Try primary URL
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        return response.content, url
    except Exception as e:
        status_errors = [f"Admin: {e}"]
        
        # Try Fallback 1: WWW
        if fallback_www:
            try:
                response = requests.get(fallback_www, headers=headers, timeout=10)
                response.raise_for_status()
                return response.content, fallback_www
            except Exception as e2:
                status_errors.append(f"WWW: {e2}")
        
        # Try Fallback 2: OAI-PMH
        if fallback_oai:
             try:
                response = requests.get(fallback_oai, headers=headers, timeout=10)
                if response.status_code == 200:
                    mods_content = check_oai_response(response.content)
                    if mods_content:
                        return mods_content, fallback_oai
                    else:
                        status_errors.append("OAI: Valid HTTP but no MODS found in response")
                else:
                    status_errors.append(f"OAI: HTTP {response.status_code}")
             except Exception as e3:
                status_errors.append(f"OAI: {e3}")

        return None, f"Failed to fetch. Details: {'; '.join(status_errors)}"

# UI Layout
main_col1, main_col2 = st.columns([0.6, 0.4], gap="large")

with main_col1:
    st.markdown('<div class="step-header"><div class="step-number">1</div><span>Select Source Data</span></div>', unsafe_allow_html=True)
    
    input_tab1, input_tab2 = st.tabs(["🌐 Pull from DORA", "πŸ“ Upload Local XML"])
    
    with input_tab1:
        dora_col1, dora_col2 = st.columns([0.7, 0.3])
        dora_input = dora_col1.text_input("PID or URL", placeholder="e.g. psi:84411", label_visibility="collapsed")
        repo_select = dora_col2.selectbox("Repo", ["psi", "eawag", "empa", "wsl"], label_visibility="collapsed")
        
        if st.button("Fetch and Load Record", use_container_width=True):
            if dora_input:
                with st.spinner("Retrieving from DORA..."):
                    content, error_or_url = fetch_from_dora(dora_input, repo_select)
                    if content:
                        filename = dora_input.replace(":", "_").replace("/", "_") + ".xml"
                        if filename.startswith("http"): filename = "dora_record.xml"
                        st.session_state.loaded_files.append({"name": filename, "content": content, "source": error_or_url})
                        st.toast(f"Loaded {filename}", icon="βœ…")
                    else:
                        st.error(f"Fetch failed: {error_or_url}")
            else:
                st.warning("Please provide a identifier first.")

    with input_tab2:
        uploaded_files = st.file_uploader("Upload MODS XML files", type=['xml'], accept_multiple_files=True, label_visibility="collapsed")

    # Display loaded files in a modern list
    if st.session_state.loaded_files:
        st.markdown("### Loaded Documents")
        for i, file_data in enumerate(st.session_state.loaded_files):
            with st.container():
                f_col1, f_col2 = st.columns([0.85, 0.15])
                f_col1.markdown(f"πŸ“„ **{file_data['name']}**")
                if f_col2.button("πŸ—‘οΈ", key=f"remove_{i}", help="Remove this file"):
                    st.session_state.loaded_files.pop(i)
                    st.rerun()

with main_col2:
    st.markdown('<div class="step-header"><div class="step-number">2</div><span>Target Format</span></div>', unsafe_allow_html=True)
    selected_template = st.selectbox("Choose the destination publication type", templates if templates else ["No templates found"], label_visibility="collapsed")
    
    st.markdown("---")
    if st.button("πŸš€ Start Conversion", disabled=not (uploaded_files or st.session_state.loaded_files) or not templates, use_container_width=True, type="primary"):
        st.session_state.start_convert = True
    else:
        st.session_state.start_convert = False

# Combine sources
all_files = []
if uploaded_files:
    for f in uploaded_files:
        all_files.append({"name": f.name, "content": f.getvalue()})
if st.session_state.loaded_files:
    all_files.extend(st.session_state.loaded_files)

if st.session_state.get("start_convert"):
    st.markdown('<div class="step-header"><div class="step-number">3</div><span>Conversion Reports</span></div>', unsafe_allow_html=True)
    
    for file_data in all_files:
        content = file_data['content']
        filename = file_data['name']
        
        # Try to decode if bytes, though lxml can parse bytes directly
        # But we pass string/bytes/path to converter
        
        template_path = os.path.join(TEMPLATE_DIR, selected_template)
        
        try:
            # result_xml is the XML string, log is the structured data dict
            result_xml, log_data = st.session_state.converter.convert(content, template_path)
            
            with st.container():
                st.markdown(f"""

                <div class="result-card">

                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">

                        <span style="font-weight: 700; font-size: 1.2rem; color: #1e3a8a;">{filename}</span>

                        <span style="background: #dbeafe; color: #1e40af; padding: 0.2rem 0.8rem; border-radius: 999px; font-size: 0.8rem; font-weight: 600;">TRANSFORMED</span>

                    </div>

                    <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1.5rem;">

                         <span style="background: #f1f5f9; padding: 0.4rem 1rem; border-radius: 8px; font-size: 0.9rem; border: 1px solid #e2e8f0;">{log_data['old_genre']}</span>

                         <span style="color: #94a3b8;">➑️</span>

                         <span style="background: #ecfdf5; color: #065f46; padding: 0.4rem 1rem; border-radius: 8px; font-size: 0.9rem; border: 1px solid #d1fae5; font-weight: 600;">{log_data['new_genre']}</span>

                    </div>

                """, unsafe_allow_html=True)

                s_col1, s_col2, s_col3 = st.columns(3)
                s_col1.metric("Transfers", len(log_data["moves"]))
                s_col2.metric("Additions", len(log_data["additions"]))
                s_col3.metric("Removals", len(log_data["deletions"]))

                with st.expander("Audit Transformation Details", expanded=False):
                    if log_data["moves"]:
                        st.write("**πŸ”„ Content Transfers**")
                        for m in log_data["moves"]:
                            st.caption(f"β€’ {m['summary']}")
                    if log_data["additions"]:
                        st.write("**✨ Smart Additions**")
                        for a in log_data["additions"]:
                            st.caption(f"β€’ {a['summary']}")
                    if log_data["deletions"]:
                        st.write("**πŸ—‘οΈ Legacy Cleanup**")
                        del_labels = [d['label'] for d in log_data["deletions"]]
                        st.caption(f"Removed {len(del_labels)} unused fields: " + ", ".join(del_labels[:8]) + ("..." if len(del_labels) > 8 else ""))

                if log_data["warnings"]:
                    for w in log_data["warnings"]:
                        st.warning(w)

                if result_xml:
                    st.download_button(
                        label=f"⬇️ Download {filename}",
                        data=result_xml,
                        file_name=f"{os.path.splitext(filename)[0]}_converted.xml",
                        mime="application/xml",
                        key=f"dl_{filename}",
                        use_container_width=True
                    )
                st.markdown('</div>', unsafe_allow_html=True)
        except Exception as e:
            st.error(f"Error converting {filename}: {e}")
            import traceback
            st.code(traceback.format_exc())