-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingle.py
More file actions
177 lines (145 loc) · 7.21 KB
/
Copy pathsingle.py
File metadata and controls
177 lines (145 loc) · 7.21 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
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import requests
import re
class DOIFormatterGUI:
def __init__(self, root):
self.root = root
self.root.title("DOI zu HTML-Li Converter")
self.root.geometry("800x600")
# Hauptframe
main_frame = ttk.Frame(root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# DOI Eingabe
ttk.Label(main_frame, text="DOI eingeben:").grid(row=0, column=0, sticky=tk.W, pady=(0, 5))
self.doi_entry = ttk.Entry(main_frame, width=50)
self.doi_entry.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
# Convert Button
convert_btn = ttk.Button(main_frame, text="HTML generieren", command=self.convert_doi)
convert_btn.grid(row=2, column=0, pady=(0, 10))
# Copy Button
copy_btn = ttk.Button(main_frame, text="Kopieren", command=self.copy_to_clipboard)
copy_btn.grid(row=2, column=1, padx=(10, 0), pady=(0, 10))
# Ausgabebereich
ttk.Label(main_frame, text="HTML <li> Element:").grid(row=3, column=0, sticky=tk.W, pady=(10, 5))
self.output_text = scrolledtext.ScrolledText(main_frame, height=20, width=80)
self.output_text.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
# Status Label
self.status_label = ttk.Label(main_frame, text="Bereit...")
self.status_label.grid(row=5, column=0, columnspan=2, sticky=tk.W)
# Grid weights für Responsivität
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(4, weight=1)
# Enter-Taste bindet an Convert
self.doi_entry.bind('<Return>', lambda event: self.convert_doi())
def convert_doi(self):
doi = self.doi_entry.get().strip()
if not doi:
messagebox.showwarning("Warnung", "Bitte geben Sie eine DOI ein.")
return
# Bereinige DOI-Format
doi = doi.replace('doi.org/', '').replace('DOI.org/', '').replace('doi:', '').replace('DOI:', '').replace('https://', '').strip()
self.status_label.config(text="Lade Daten von CrossRef...")
self.root.update()
try:
html_output = self.format_doi_to_html(doi)
self.output_text.delete(1.0, tk.END)
self.output_text.insert(1.0, html_output)
self.status_label.config(text="HTML erfolgreich generiert.")
except Exception as e:
self.status_label.config(text=f"Fehler: {e}")
messagebox.showerror("Fehler", f"Fehler beim Verarbeiten: {e}")
def format_doi_to_html(self, doi):
"""
Formatiert eine DOI ins HTML-Format durch Abrufen der CrossRef-Daten
"""
headers = {
'Accept': 'application/json'
}
url = f"https://api.crossref.org/works/{doi}"
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
message = data.get('message', {})
except requests.exceptions.HTTPError as http_err:
raise Exception(f"DOI {doi} nicht gefunden oder API-Problem (HTTP {http_err.response.status_code})")
except requests.exceptions.RequestException as req_err:
raise Exception(f"Netzwerkproblem beim Abrufen von DOI {doi}: {req_err}")
except ValueError:
raise Exception(f"Ungültige JSON-Antwort für DOI {doi}")
try:
# Autoren
authors_list = []
if 'author' in message and message['author']:
for author_data in message['author']:
name_parts = []
if 'given' in author_data:
name_parts.append(author_data['given'])
if 'family' in author_data:
name_parts.append(author_data['family'])
authors_list.append(" ".join(name_parts))
formatted_authors = ", ".join(authors_list)
# Titel
title_value = ""
if 'title' in message and message['title']:
title_value = message['title'][0] if isinstance(message['title'], list) else message['title']
# Journal, Volume, Pages, Year
journal_name = ""
if 'container-title' in message and message['container-title']:
journal_name = message['container-title'][0] if isinstance(message['container-title'], list) else message['container-title']
volume = message.get('volume', '')
pages = message.get('page', '')
year = ""
if 'published-print' in message and 'date-parts' in message['published-print']:
year = str(message['published-print']['date-parts'][0][0])
elif 'published-online' in message and 'date-parts' in message['published-online']:
year = str(message['published-online']['date-parts'][0][0])
elif 'created' in message and 'date-parts' in message['created']:
year = str(message['created']['date-parts'][0][0])
# Zusammenbau der Journal-Zeile
journal_details_parts = []
if journal_name:
journal_details_parts.append(journal_name)
if volume:
journal_details_parts.append(f"vol. {volume}")
if year:
journal_details_parts.append(year)
if pages:
journal_details_parts.append(f"pp. {pages}")
journal_citation = ", ".join(journal_details_parts)
if journal_citation:
journal_citation += "."
# DOI Link
doi_full_url = f"https://doi.org/{doi}"
# HTML-Output erstellen
html_output = f"""<li>
{formatted_authors}<br>
<strong>{title_value}</strong><br>
{journal_citation}<br>
DOI: <a href="{doi_full_url}" target="_blank">{doi}</a>
</li>"""
return html_output
except KeyError as ke:
raise Exception(f"Erwartetes Feld '{ke}' nicht in CrossRef-Daten gefunden")
except Exception as e:
raise Exception(f"Unbekannter Fehler beim Verarbeiten der CrossRef-Daten: {e}")
def copy_to_clipboard(self):
"""
Kopiert den HTML-Inhalt in die Zwischenablage
"""
content = self.output_text.get(1.0, tk.END).strip()
if content:
self.root.clipboard_clear()
self.root.clipboard_append(content)
self.status_label.config(text="HTML in Zwischenablage kopiert.")
else:
messagebox.showwarning("Warnung", "Kein Inhalt zum Kopieren vorhanden.")
def main():
root = tk.Tk()
app = DOIFormatterGUI(root)
root.mainloop()
if __name__ == "__main__":
main()