mgokg commited on
Commit
d6b5c62
·
verified ·
1 Parent(s): d42b7f7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -106
app.py CHANGED
@@ -1,109 +1,53 @@
1
  import gradio as gr
2
- from docling.datamodel.base_models import InputFormat
3
- from docling.document_converter import DocumentConverter
4
- import tempfile
5
- import io
6
- import re
7
- import os
8
- import language_tool_python
9
- import html
10
- tool = language_tool_python.LanguageTool('de-DE')
11
- bad_string = """<br>&lt;!<span style="color: red; text-decoration: underline;" title="Möglicher Tippfehler gefunden. (Vorschläge: - -image)">-- image</span> <span style="color: red; text-decoration: underline;" title="Möchten Sie einen Pfeil verwenden? (Vorschläge: →, ⇾, ⇉)">--&gt;</span><br>"""
12
- def check_spelling(text_input: str) -> str:
13
- """Prüft den Text mit LanguageTool und markiert Fundstellen in HTML."""
14
- if tool is None:
15
- return "❌ **Fehler:** LanguageTool konnte nicht geladen werden."
16
- text = text_input or ""
17
- if not text.strip():
18
- return "*Bitte lade eine Datei hoch oder füge Text ein...*"
19
- if text.startswith("❌") or text.startswith("Fehler"):
20
- return text
21
- matches = tool.check(text)
22
- if not matches:
23
- return "<p style='color: green;'>✅ Keine Fehler gefunden!</p>"
24
- # HTML-Aufbau für die Anzeige der Fehler
25
- parts = []
26
- text_len = len(text)
27
- last_idx = text_len
28
- for match in reversed(matches):
29
- start = match.offset
30
- end = match.offset + match.error_length
31
- parts.append(html.escape(text[end:last_idx]))
32
- word = text[start:end]
33
- suggestions = ", ".join(match.replacements[:3]) if match.replacements else "keine Vorschläge"
34
- error_html = (
35
- f'<span style="color: red; text-decoration: underline;" '
36
- f'title="{html.escape(match.message)} (Vorschläge: {html.escape(suggestions)})">'
37
- f'{html.escape(word)}</span>'
38
- )
39
- parts.append(error_html)
40
- last_idx = start
41
- parts.append(html.escape(text[:last_idx]))
42
- html_texte = "".join(reversed(parts)).replace("\n\n", "<br><br>")
43
- html_text = html_texte.replace("\n", "<br>")
44
- html_result = f"<div><strong>⚠️ {len(matches)} Fehler gefunden</strong><br><br>{html_text}</div>"
45
- return html_result
46
-
47
- def process_pdf(pdf_file):
48
- if pdf_file is None:
49
- return None, "Bitte laden Sie ein PDF hoch."
50
- try:
51
- converter = DocumentConverter()
52
- result = converter.convert(pdf_file.name)
53
- extracted_text = result.document.export_to_markdown()
54
- return extracted_text.replace(bad_string, "")
55
- except Exception as e:
56
- return f"Fehler bei der Verarbeitung: {str(e)}"
57
-
58
- def process_text(text_input):
59
- """Verarbeitet direkt eingegebenen Text und prüft die Rechtschreibung."""
60
- if not text_input or not text_input.strip():
61
- return "*Bitte Text eingeben...*"
62
- return check_spelling(text_input)
63
-
64
- def process_pdf_with_spelling(pdf_file):
65
- """Verarbeitet PDF und führt anschließend Rechtschreibprüfung durch."""
66
- extracted = process_pdf(pdf_file)
67
- if extracted is None or str(extracted).startswith("Fehler"):
68
- return extracted
69
- #return extracted
70
- return check_spelling(extracted)
71
-
72
- # Gradio Interface
73
- with gr.Blocks(title="Smart PDF OCR (Column-Aware)") as demo:
74
- gr.Markdown("# 📑 Smart PDF Layout-Aware OCR")
75
-
76
- with gr.Tabs():
77
- # --- Tab 1: PDF Upload ---
78
- with gr.TabItem("📄 PDF hochladen"):
79
- with gr.Row():
80
- pdf_input = gr.File(label="PDF hochladen", file_types=[".pdf"])
81
-
82
- with gr.Row():
83
- text_output = gr.Markdown(label="Extrahierter Text (Markdown Format)")
84
-
85
- submit_btn = gr.Button("Dokument analysieren", variant="primary")
86
- submit_btn.click(fn=process_pdf_with_spelling, inputs=pdf_input, outputs=text_output)
87
-
88
- # --- Tab 2: Text direkt eingeben ---
89
- with gr.TabItem("✏️ Text eingeben"):
90
- with gr.Row():
91
- text_input = gr.Textbox(
92
- label="Text eingeben",
93
- placeholder="Geben Sie hier Ihren deutschen Text ein...",
94
- lines=10,
95
- max_lines=30,
96
- )
97
-
98
- with gr.Row():
99
- spell_output = gr.HTML(label="Rechtschreibprüfung")
100
-
101
- with gr.Row():
102
- check_btn = gr.Button("Rechtschreibung prüfen", variant="primary")
103
- clear_btn = gr.Button("Leeren", variant="secondary")
104
-
105
- check_btn.click(fn=process_text, inputs=text_input, outputs=spell_output)
106
- clear_btn.click(fn=lambda: ("", ""), inputs=None, outputs=[text_input, spell_output])
107
-
108
  if __name__ == "__main__":
109
  demo.launch()
 
1
  import gradio as gr
2
+ from spellchecker import SpellChecker
3
+
4
+ # 1. Logik: Rechtschreibprüfung initialisieren (Deutsch)
5
+ spell = SpellChecker(language='de')
6
+
7
+ def process_text(text):
8
+ if not text or text.strip() == "":
9
+ return "Bitte gib einen Text ein."
10
+
11
+ words = text.split()
12
+ misspelled = spell.unknown([w.strip('.,!?:;') for w in words])
13
+
14
+ corrected_words = []
15
+ for word in words:
16
+ clean = word.strip('.,!?:;')
17
+ # Wenn das Wort falsch geschrieben ist, Vorschlag in Klammern zeigen
18
+ if clean.lower() in [m.lower() for m in misspelled]:
19
+ correction = spell.correction(clean)
20
+ corrected_words.append(f"❌ {word} ({correction}?)")
21
+ else:
22
+ corrected_words.append(word)
23
+
24
+ return " ".join(corrected_words)
25
+
26
+ # 2. UI: Gradio Interface Aufbau
27
+ with gr.Blocks() as demo:
28
+ gr.Markdown("# 📝 Deutsche Rechtschreibprüfung")
29
+
30
+ with gr.Column():
31
+ text_input = gr.Textbox(lines=5, label="Dein Text", placeholder="Schreibe hier etwas auf Deutsch...")
32
+ spell_output = gr.Textbox(label="Ergebnis / Korrekturvorschläge")
33
+
34
+ with gr.Row():
35
+ check_btn = gr.Button("Rechtschreibung prüfen", variant="primary")
36
+ clear_btn = gr.Button("Leeren", variant="secondary")
37
+
38
+ # 3. Events: Verknüpfung der Buttons mit der Logik
39
+ check_btn.click(
40
+ fn=process_text,
41
+ inputs=text_input,
42
+ outputs=spell_output
43
+ )
44
+
45
+ clear_btn.click(
46
+ fn=lambda: ("", ""),
47
+ inputs=None,
48
+ outputs=[text_input, spell_output]
49
+ )
50
+
51
+ # App starten
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  if __name__ == "__main__":
53
  demo.launch()