pdf_path = "PID_Beispiel.pdf" # Ensure this PDF is in the same directory or provide the full path
csv_filename = "individual_bubble_candidates_final.csv" # Output filename
--- Geometric Filters for Initial Detection ---
These might need adjustment based on the specific PDF. Start broad, then narrow down.
Values based on typical instrument bubbles (~40x40 points) but allowing variation.
min_area = 1600 # Lower bound for area (points squared)
max_area = 2500 # Upper bound for area
min_aspect = 0.4 # Minimum width/height ratio
max_aspect = 1.6 # Maximum width/height ratio
min_segments = 30 # Minimum number of drawing path segments (heuristics for complexity)
max_segments = 100 # Maximum number of drawing path segments
--- Text Extraction Expansion ---
How many points to expand the bounding box for text extraction
text_extraction_expansion = 2
--- Main Script ---
def process_pid_pdf_individual(pdf_filepath, output_csv_filepath):
"""
Identifies individual instrument bubbles based on geometric properties,
extracts text for each, and saves them to a CSV file.
Grouping logic is explicitly excluded.
"""
try:
doc = fitz.open(pdf_filepath)
except Exception as e:
print(f"Error opening PDF file '{pdf_filepath}': {e}")
return
code
Assistant
User
gebe den ganzen vollstndigen code
Assistant
User
%Run -c $EDITOR_CONTENT
Processing PDF: PID_Beispiel.pdf
Phase 1: Identifying individual bubble candidates with splitting...
Page 1/3: Analyzing 597 drawing objects.
Traceback (most recent call last):
File "", line 242, in
File "", line 101, in process_pid_pdf_individual
File "", line 44, in split_drawing_if_possible
File "", line 22, in point_distance
TypeError: unsupported operand type(s) for ** or pow(): 'Point' and 'int'
Assistant
User
vollstaendigen code
Assistant
identified_bubbles = []
print(f"Processing PDF: {pdf_filepath}")
print("Phase 1: Identifying individual bubble candidates...")
# --- Phase 1: Find potential candidates based on geometry ---
for page_num in range(len(doc)):
page = doc[page_num]
drawings = page.get_drawings()
print(f"Page {page_num + 1}/{len(doc)}: Analyzing {len(drawings)} drawing objects.")
for drawing_index, drawing in enumerate(drawings):
items = drawing.get("items", [])
num_segments = len(items)
# --- Apply Filters ---
# Filter 1: Segment count
if not (min_segments <= num_segments <= max_segments):
continue
# Filter 2: Closed Path Heuristic (Simplified)
# Primarily trusts the 'closed' flag if available, or checks start/end point proximity.
# This might still filter out some valid shapes if the PDF drawing is unusual.
is_closed = drawing.get("closed", False)
if not is_closed and items:
first_point, last_point = None, None
for item_type, *coords in items:
if item_type in ('l', 'c', 're') and len(coords) >= 2:
if first_point is None: first_point = (coords[0], coords[1])
last_point = (coords[-2], coords[-1])
if first_point and last_point and \
abs(first_point[0] - last_point[0]) < 1.0 and \
abs(first_point[1] - last_point[1]) < 1.0:
is_closed = True
# Uncomment the next line ONLY if the closed check seems to be removing valid bubbles
# if not is_closed: continue
# Filter 3: Get and validate bounding box
bbox_obj = drawing.get("rect")
bbox = None
if bbox_obj:
bbox = tuple(bbox_obj) if not hasattr(bbox_obj, "x0") else (bbox_obj.x0, bbox_obj.y0, bbox_obj.x1, bbox_obj.y1)
if not bbox or bbox[0] >= bbox[2] or bbox[1] >= bbox[3]: # If invalid or missing, try calculating
xs, ys = [], []
for item_type, *coords in items:
if len(coords) >= 2:
for i in range(0, len(coords), 2):
if i + 1 < len(coords) and isinstance(coords[i], (int, float)) and isinstance(coords[i+1], (int, float)):
xs.append(coords[i]); ys.append(coords[i+1])
if xs and ys: bbox = (min(xs), min(ys), max(xs), max(ys))
else: bbox = None
if bbox is None or bbox[0] >= bbox[2] or bbox[1] >= bbox[3]: continue # Skip if still invalid
# Filter 4: Calculate and check geometry (Area, Aspect Ratio)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
if width <= 1 or height <= 1: continue
area = width * height
aspect_ratio = width / height if height != 0 else 0
# --- Optional Debug Print (before final area/aspect check) ---
# print(f" Checking Drawing {drawing_index}: Segs={num_segments}, Closed={is_closed}, Area={area:.1f}, AR={aspect_ratio:.2f}, BBox={bbox}")
# ---
if not (min_area <= area <= max_area): continue
if not (min_aspect <= aspect_ratio <= max_aspect): continue
# --- Candidate passed all filters ---
candidate_id = f"p{page_num+1}_d{drawing_index}"
# --- Optional Debug Print (for successful candidates) ---
# print(f" >>> Found Candidate {candidate_id}: Area={area:.1f}, AR={aspect_ratio:.2f}, Segs={num_segments}")
# ---
identified_bubbles.append({
"id": candidate_id, "page": page_num + 1, "bbox": bbox,
"segments": num_segments, "area": area, "aspect_ratio": aspect_ratio,
"text": "" # Placeholder for text
})
print(f"Phase 1 complete. Found {len(identified_bubbles)} potential bubble candidates meeting geometric criteria.")
if not identified_bubbles:
print("No potential bubble candidates found. Try adjusting the geometric filters (area, aspect ratio, segments) in the script. Exiting.")
doc.close()
return
# --- Phase 2: Extract text for each identified bubble ---
print("Phase 2: Extracting text for individual candidates...")
for bubble in identified_bubbles:
page_index = bubble["page"] - 1
page = doc[page_index]
try:
rect = fitz.Rect(bubble["bbox"])
# Expand box slightly for text extraction
rect.x0 -= text_extraction_expansion
rect.y0 -= text_extraction_expansion
rect.x1 += text_extraction_expansion
rect.y1 += text_extraction_expansion
text = page.get_text("text", clip=rect, sort=True).strip()
text = ' '.join(text.split()) # Clean whitespace
bubble["text"] = text
except Exception as e:
print(f" Warning: Error extracting text for candidate {bubble['id']}: {e}")
bubble["text"] = "" # Ensure text is empty on error
print("Phase 2 complete. Text extraction finished.")
# --- Phase 3: Prepare Final Output (No Grouping) ---
# Phase 3 is now trivial as we are not grouping. We just use the list from Phase 1/2.
print("Phase 3: Finalizing individual bubbles (No Grouping).")
# Optional: Sort final list for consistent output
identified_bubbles.sort(key=lambda b: (b['page'], b['bbox'][1], b['bbox'][0]))
# --- Phase 4: Write the results to a CSV file ---
print(f"Phase 4: Writing {len(identified_bubbles)} individual bubble results to CSV: {output_csv_filepath}")
if identified_bubbles:
try:
with open(output_csv_filepath, "w", newline='', encoding="utf-8") as csvfile:
fieldnames = [
'page', 'x0', 'y0', 'x1', 'y1', # Coordinates of the bubble's bbox
'text', # The extracted text
'area', # Geometric properties (optional, for review)
'aspect_ratio',
'segments'
]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for bubble in identified_bubbles:
x0, y0, x1, y1 = bubble["bbox"]
writer.writerow({
"page": bubble["page"],
"x0": f"{x0:.2f}", "y0": f"{y0:.2f}",
"x1": f"{x1:.2f}", "y1": f"{y1:.2f}",
"text": bubble["text"],
"area": f"{bubble['area']:.1f}",
"aspect_ratio": f"{bubble['aspect_ratio']:.2f}",
"segments": bubble["segments"]
})
print(f"Processing complete. Results successfully saved to '{output_csv_filepath}'.")
except IOError as e:
print(f"Error writing to CSV file '{output_csv_filepath}': {e}")
except Exception as e:
print(f"An unexpected error occurred during CSV writing: {e}")
else:
print("No final bubbles were identified to write to the CSV file.")
doc.close()
print("PDF document closed.")
--- Script Execution ---
if name == "main":
if os.path.exists(pdf_path):
process_pid_pdf_individual(pdf_path, csv_filename)
else:
print(f"Error: PDF file not found at specified path: {pdf_path}")
print("Please ensure the PDF file exists in the same directory as the script or provide the correct path.")
die formen sind manschmal direk aneinander und werden so nicht erkannt weil sie sich linien teilen
Du hast Recht, wenn Formen direkt aneinanderstoßen und sich Linien bzw. Pfade teilen, kann es schwierig sein, sie als einzelne, getrennte "Bubbles" zu erkennen. Die aktuelle Logik betrachtet jede Zeichnung (Drawing) isoliert, und wenn Formen sich die Kanten teilen, sind sie oft als ein einziger Pfad oder Zeichenobjekt erkannt – also als eine zusammenhängende Einheit.
Problem:
Überlappende oder aneinandergrenzende Formen sind als ein einziger Pfad.
Dadurch können einzelne Blasen nicht sauber extrahiert werden.
Mögliche Lösungsansätze
1. Formen "entflechten" / Aufteilen anhand von Geometrie
Das ist schwierig, weil die PDF-Zeichnungs-APIs (hier page.get_drawings()) nicht die Strukturen einzelner Formen angeben, sondern nur "Pfadobjekte".
Man müsste Pfade zerlegen, was komplex ist.
2. Erkennung und Extraktion von "gemeinsamen Linien" und Aufteilung der Pfade
Diese Funktion bietet get_drawings() nicht von Haus. Du müsstest entweder:
Pfade manuell segmentieren und filtern, z.B. mit mehr Geometrie-Logik (Linien- und Kurven-Segmente),
Oder stattdessen Ansätze auf Bildebene verfolgen (page.get_pixmap()) und dann z.B. mit Bildverarbeitung (OpenCV vorhandene Kreise, Konturen) erkennen.
3. Verwenden von Textboxen/Annotationen anstelle von Pfaden, falls vorhanden
Falls Deine "Bubbles" Textboxen oder Annotationen sind, könntest Du damit arbeiten statt auf Pfade zu setzen.
Falls für die gemeinsame Linie die Anzahl der Segmente extrem hoch ist (also "zusammengesetzter Pfad"), kannst Du auf das Filtern der Segmentanzahl achten:
Große Segmentanzahl => wahrscheinlich mehrere zusammenhängende Formen
Kleine Segmentanzahl => einzelne Blase
Dann könntest Du größere Mehrsegment-Pfade mit einer niedrigeren Priorität behandeln oder versuchen, sie in rechteckige Bereiche zu splitten.
Praktische Erweiterung für Deinen Code (Stichworte)
Ich zeige hier beispielhaft, wie man Zeichnungen (Pfade mit vielen Segmenten) trennen könnte, indem man mit den Pfadpunkten arbeitet und versucht, über Lücken zu segmentieren:
python
def split_drawing_if_possible(drawing):
"""
Versucht eine Zeichnung in mehrere Pfade (Bubbles) zu splitten,
basierend auf Positionsabständen zwischen Liniensegmenten.
Gibt eine Liste von Bubbles (jeweils dicts mit bbox, items, etc.) zurück.
"""
items = drawing.get("items", [])
if not items:
return []
# Beispielhafte Logik: gruppiere Segmente, wenn die Startpunkt-Abstände groß sind.
groups = []
current_group = []
threshold_dist = 10 # Abstand in Punkten, um Formteile zu trennen
def point_distance(p1, p2):
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
last_end_point = None
for item in items:
item_type, *coords = item
if item_type in ('l','c','re'):
start_point = (coords[0], coords[1])
if last_end_point is not None:
dist = point_distance(start_point, last_end_point)
if dist > threshold_dist and current_group:
# Abstand groß genug => neue Gruppe
groups.append(current_group)
current_group = []
current_group.append(item)
last_end_point = (coords[-2], coords[-1])
else:
# Andere Items, einfach mitschleifen
current_group.append(item)
if current_group:
groups.append(current_group)
bubbles = []
for idx, group in enumerate(groups):
xs, ys = [], []
for item in group:
itype, *c = item
for i in range(0,len(c),2):
xs.append(c[i])
ys.append(c[i+1])
if xs and ys:
bbox = (min(xs), min(ys), max(xs), max(ys))
bubbles.append({
"bbox": bbox,
"items": group,
# Ergänze weitere Daten wie in Deinem existierenden Code
})
return bubbles
Integrieren in Deine bestehende Pipeline:
Ersetze in der Schleife, in der Du drawings durchläufst, jedes drawing durch dessen Splitting mit split_drawing_if_possible.
Prüfe danach jede Teildrawing separat.
Dadurch kannst Du größere, verknüpfte Pfade in kleinere "Blasen" auftrennen.
Fazit / Empfehlung
Mit PyMuPDF alleine ist das problematisch. Die Pfade sind die notwendige "Atom-Einheit".
Durch die Splittung von Pfaden über Lücken kannst Du bessern erkennen.
Ambitioniertere Ansätze erfordern Bildverarbeitung (OCR + Bildsegmentierung mit OpenCV etc.).
Passe die threshold_dist an, um besser zwischen zusammenhängenden und getrennten Formen zu unterscheiden.
Optional: Visualisiere, was erkannt wird (z.B. mit Rechtecken), um Filterparameter zu justieren.
Falls Du möchtest, kann ich Dir helfen, mehr Beispielcode einzubauen oder Ansätze für Bildverarbeitung zeigen.
Meld Dich gern!
Hier ist der komplett überarbeitete und kommentierte Python-Code, der die Gruppierung verbundener Pfade in einzelne "Bubbles" versucht, indem Zeichnungen gemäß Abstand zwischen Liniensegmenten aufgeteilt werden. So können direkt aneinanderliegende Formen besser erkannt werden:
python
import fitz # PyMuPDF - pip install pymupdf
import csv
import os
# --- Configuration ---
pdf_path = "PID_Beispiel.pdf" # Stelle sicher, dass das PDF im selben Verzeichnis liegt oder gib den vollen Pfad an
csv_filename = "individual_bubble_candidates_final.csv" # Ausgabe-CSV-Datei
# --- Geometric Filters for Initial Detection ---
min_area = 1600 # Fläche (in Punkten²) unteren Schranke
max_area = 2500 # Fläche oberen Schranke
min_aspect = 0.4 # Mindest-Seitenverhältnis (Breite/Höhe)
max_aspect = 1.6 # Maximal-Seitenverhältnis
min_segments = 10 # Minimum Segmentanzahl (etwas gesenkt, da wir Splitting machen)
max_segments = 100 # Maximum Segmentanzahl
# --- Text Extraction Expansion ---
text_extraction_expansion = 2 # Punkte zum Erweitern der Bounding Box für Text-Extraktion
# --- Hilfsfunktion: Abstand zweier Punkte ---
def point_distance(p1, p2):
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
# --- Funktion zum Splitten einer Zeichnung in mögliche Einzelformen (Bubbles) ---
def split_drawing_if_possible(drawing, threshold_dist=10):
"""
Teilt ein einzelnes Drawing-Objekt in kleinere Gruppen von Segmenten,
wenn innerhalb der Pfadpunkte großer Abstand ist.
Rückgabe: List von Zeichnungen (je dict mit mindestens 'items' und 'rect')
"""
items = drawing.get("items", [])
if not items:
return []
groups = []
current_group = []
last_end_point = None
for item in items:
item_type, *coords = item
if item_type in ('l','c','re'):
start_point = (coords[0], coords[1])
if last_end_point is not None:
dist = point_distance(start_point, last_end_point)
if dist > threshold_dist and current_group:
groups.append(current_group)
current_group = []
current_group.append(item)
last_end_point = (coords[-2], coords[-1])
else:
# Andere Items (z.B. move, curve) mit anhängen
current_group.append(item)
if current_group:
groups.append(current_group)
# Für jede Gruppe berechnen wir eine Boundingbox und geben ein neues dict zurück
splitted_drawings = []
for group in groups:
xs, ys = [], []
for item in group:
itype, *c = item
for i in range(0,len(c),2):
xs.append(c[i])
ys.append(c[i+1])
if not xs or not ys:
continue
bbox = (min(xs), min(ys), max(xs), max(ys))
splitted_drawings.append({
"items": group,
"rect": bbox,
"closed": drawing.get("closed", False)
})
return splitted_drawings
# --- Hauptfunktion ---
def process_pid_pdf_individual(pdf_filepath, output_csv_filepath):
"""
Identifiziert individuelle Instrumentenblasen,
extrahiert Text und speichert die Ergebnisse in einer CSV-Datei.
Integriert die Splitting-Logik für zusammenhängende Formen.
"""
try:
doc = fitz.open(pdf_filepath)
except Exception as e:
print(f"Error opening PDF file '{pdf_filepath}': {e}")
return
identified_bubbles = []
print(f"Processing PDF: {pdf_filepath}")
print("Phase 1: Identifying individual bubble candidates with splitting...")
for page_num in range(len(doc)):
page = doc[page_num]
drawings = page.get_drawings()
print(f"Page {page_num + 1}/{len(doc)}: Analyzing {len(drawings)} drawing objects.")
for drawing_index, drawing in enumerate(drawings):
# Splitte ggf. komplexe Zeichnungen (zusammenhängende Formen)
splitted = split_drawing_if_possible(drawing, threshold_dist=10)
# Falls kein Split stattfand, enthalten wir den originalen Pfad:
if not splitted:
splitted = [drawing]
for split_index, d in enumerate(splitted):
items = d.get("items", [])
num_segments = len(items)
if not (min_segments <= num_segments <= max_segments):
continue
# Prüfe "geschlossen"-Flag
is_closed = d.get("closed", False)
if not is_closed and items:
first_point, last_point = None, None
for item_type, *coords in items:
if item_type in ('l', 'c', 're') and len(coords) >= 2:
if first_point is None: first_point = (coords[0], coords[1])
last_point = (coords[-2], coords[-1])
if first_point and last_point and \
abs(first_point[0] - last_point[0]) < 1.0 and \
abs(first_point[1] - last_point[1]) < 1.0:
is_closed = True
# Uncomment if you want to filter non-closed paths:
# if not is_closed: continue
# Bounding Box aus dict oder berechnen
bbox_obj = d.get("rect")
bbox = None
if bbox_obj:
bbox = tuple(bbox_obj) if not hasattr(bbox_obj, "x0") else (bbox_obj.x0, bbox_obj.y0, bbox_obj.x1, bbox_obj.y1)
if not bbox or bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
# Fallback Berechnung aus Punkten
xs, ys = [], []
for item_type, *coords in items:
if len(coords) >= 2:
for i in range(0, len(coords), 2):
if i + 1 < len(coords) and isinstance(coords[i], (int, float)) and isinstance(coords[i+1], (int, float)):
xs.append(coords[i])
ys.append(coords[i+1])
if xs and ys:
bbox = (min(xs), min(ys), max(xs), max(ys))
else:
bbox = None
if bbox is None or bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
continue
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
if width <= 1 or height <= 1:
continue
area = width * height
aspect_ratio = width / height if height != 0 else 0
if not (min_area <= area <= max_area):
continue
if not (min_aspect <= aspect_ratio <= max_aspect):
continue
candidate_id = f"p{page_num+1}_d{drawing_index}_s{split_index}"
identified_bubbles.append({
"id": candidate_id,
"page": page_num + 1,
"bbox": bbox,
"segments": num_segments,
"area": area,
"aspect_ratio": aspect_ratio,
"text": ""
})
print(f"Phase 1 complete. Found {len(identified_bubbles)} potential bubble candidates after splitting.")
if not identified_bubbles:
print("No potential bubble candidates found. Versuch die Filterparameter anzupassen (area, aspect_ratio, segments).")
doc.close()
return
print("Phase 2: Extracting text for individual candidates...")
for bubble in identified_bubbles:
page_index = bubble["page"] - 1
page = doc[page_index]
try:
rect = fitz.Rect(bubble["bbox"])
rect.x0 -= text_extraction_expansion
rect.y0 -= text_extraction_expansion
rect.x1 += text_extraction_expansion
rect.y1 += text_extraction_expansion
text = page.get_text("text", clip=rect, sort=True).strip()
text = ' '.join(text.split()) # Whitespace säubern
bubble["text"] = text
except Exception as e:
print(f" Warning: Fehler beim Text extrahieren für Candidate {bubble['id']}: {e}")
bubble["text"] = ""
print("Phase 2 complete. Text extraction finished.")
print("Phase 3: Sorting final bubbles for consistent output.")
identified_bubbles.sort(key=lambda b: (b['page'], b['bbox'][1], b['bbox'][0]))
print(f"Phase 4: Writing {len(identified_bubbles)} individual bubbles to CSV: {output_csv_filepath}")
if identified_bubbles:
try:
with open(output_csv_filepath, "w", newline='', encoding="utf-8") as csvfile:
fieldnames = [
'page', 'x0', 'y0', 'x1', 'y1',
'text',
'area',
'aspect_ratio',
'segments'
]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for bubble in identified_bubbles:
x0, y0, x1, y1 = bubble["bbox"]
writer.writerow({
"page": bubble["page"],
"x0": f"{x0:.2f}", "y0": f"{y0:.2f}",
"x1": f"{x1:.2f}", "y1": f"{y1:.2f}",
"text": bubble["text"],
"area": f"{bubble['area']:.1f}",
"aspect_ratio": f"{bubble['aspect_ratio']:.2f}",
"segments": bubble["segments"]
})
print(f"Processing complete. Ergebnisse erfolgreich gespichert in '{output_csv_filepath}'.")
except IOError as e:
print(f"Error writing to CSV file '{output_csv_filepath}': {e}")
except Exception as e:
print(f"Unexpected error during CSV writing: {e}")
else:
print("Keine finalen Blasen zum Schreiben in die CSV gefunden.")
doc.close()
print("PDF-Dokument geschlossen.")
# --- Script Execution ---
if __name__ == "__main__":
if os.path.exists(pdf_path):
process_pid_pdf_individual(pdf_path, csv_filename)
else:
print(f"Error: PDF file not found at specified path: {pdf_path}")
print("Bitte stelle sicher, dass die PDF-Datei existiert oder gib den korrekten Pfad an.")
Erläuterungen zur Anpassung:
split_drawing_if_possible: Erkennt große Sprünge zwischen Segmentstart- und Endpunkten und splittet die Zeichnung in mehrere Teilpfade.
In Phase 1 läuft nun jede drawing durch die Split-Funktion, die einzelne Unterformen extrahiert.
Es folgen weiterhin die Filter nach Anzahl Segmente, Fläche, Seitenverhältnis etc.
Jeder Split erhält eine individuelle ID mit Zusatz _s{split_index}, damit Du die Teilsplits nachvollziehen kannst.
Die Text-Extraktion erfolgt auf den individuellen kleineren Bounding-Boxen, was die Trennung verbessert.
Minimal gesenkte min_segments-Schwelle, da Splitting zu kleineren Gruppen führen kann.
Tipp:
Wenn Du viele oder zu wenige Ergebnisse bekommst, passe die Parameter an:
threshold_dist in split_drawing_if_possible: Abstand, ab dem Pfade getrennt werden
min_area, max_area, min_aspect, max_aspect für die Filterung
min_segments und max_segments ebenfalls, abhängig von Deinen PDF-Pfaden
Falls Du noch erstellen willst, dass Kanten visueller geprüft werden, kannst Du mit page.draw_rect() (für Debug-Ausgaben) experimentieren.
Wenn Du Unterstützung zu erweiterten Lösungen (OCR, Bildverarbeitung) brauchst, sag gern Bescheid!
Der Fehler TypeError: unsupported operand type(s) for ** or pow(): 'Point' and 'int' tritt auf, weil an der Stelle, wo point_distance(p1, p2) den Abstand zwischen zwei Punkten berechnet, p1 oder p2 nicht wie erwartet Tupel (x, y) sind, sondern Objekte vom Typ fitz.Point. Diese können nicht direkt so behandelt werden, wie es der Code erwartet.
Problemstelle
In der Funktion split_drawing_if_possible ist die Variable last_end_point beim Zugriff tatsächlich ein fitz.Point-Objekt und start_point ist wahrscheinlich ein Tupel (float, float), oder auch fitz.Point. Das führt zum Fehler bei point_distance.
Lösung
Du kannst überall sicherheitshalber tuple() auf die Punkte anwenden, bzw. wenn es fitz.Point ist, konvertierst Du es manuell in ein Tupel oder greifst auf .x und .y zu.
Zum Beispiel so:
python
def point_to_tuple(p):
if hasattr(p, "x") and hasattr(p, "y"):
return (p.x, p.y)
return p # Falls schon Tupel
def point_distance(p1, p2):
p1 = point_to_tuple(p1)
p2 = point_to_tuple(p2)
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
Und im Split-Code sicherstellen, dass die Punkte als Tupel vorliegen:
Das ist in Ordnung da coords aus items Listen von floats sind, denke ich.
Das Problem entsteht aber, wenn last_end_point vorher auf ein fitz.Point gesetzt wurde.
Gesamtfix
In Deinem Skript kannst Du die Funktion point_distance so ersetzen:
python
def point_to_tuple(p):
# Konvertiert fitz.Point in Tupel
if hasattr(p, "x") and hasattr(p, "y"):
return (p.x, p.y)
return p
def point_distance(p1, p2):
p1 = point_to_tuple(p1)
p2 = point_to_tuple(p2)
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
Dann in split_drawing_if_possible initialisiere last_end_point mit None, aber immer Tupel speichern, z.B.:
python
last_end_point = None
for item in items:
item_type, *coords = item
if item_type in ('l','c','re'):
start_point = (coords[0], coords[1])
if last_end_point is not None:
dist = point_distance(start_point, last_end_point)
if dist > threshold_dist and current_group:
groups.append(current_group)
current_group = []
current_group.append(item)
last_end_point = (coords[-2], coords[-1])
else:
current_group.append(item)
So stellst Du sicher, dass last_end_point und start_point immer Tupel sind.
Zusammenfassung:
Passe point_distance an, damit fitz.Point sicher zu Tupel wird.
Stelle sicher, dass last_end_point und start_point Tupel sind.
Vermeide fitz.Point-Objekte in der Distanzberechnung.
Falls Du möchtest, kann ich Dir den kompletten korrigierten Code mit dieser Anpassung noch einmal senden. Sage einfach Bescheid!
Hier der vollständige, überarbeitete Code mit der Korrektur für die Punktabstände (Umwandlung von fitz.Point zu Tupel) und der Splitting-Funktion. Das behebt den TypeError:
python
import fitz # PyMuPDF - pip install pymupdf
import csv
import os
# --- Configuration ---
pdf_path = "PID_Beispiel.pdf" # Stelle sicher, dass das PDF im selben Verzeichnis liegt oder gib den vollen Pfad an
csv_filename = "individual_bubble_candidates_final.csv" # Ausgabe-CSV-Datei
# --- Geometric Filters for Initial Detection ---
min_area = 1600 # Fläche (in Punkten²) unteren Schranke
max_area = 2500 # Fläche oberen Schranke
min_aspect = 0.4 # Mindest-Seitenverhältnis (Breite/Höhe)
max_aspect = 1.6 # Maximal-Seitenverhältnis
min_segments = 10 # Minimum Segmentanzahl (etwas gesenkt, da wir Splitting machen)
max_segments = 100 # Maximum Segmentanzahl
# --- Text Extraction Expansion ---
text_extraction_expansion = 2 # Punkte zum Erweitern der Bounding Box für Text-Extraktion
# --- Hilfsfunktion: Umwandlung fitz.Point zu Tupel ---
def point_to_tuple(p):
if hasattr(p, "x") and hasattr(p, "y"):
return (p.x, p.y)
return p
# --- Hilfsfunktion: Abstand zweier Punkte ---
def point_distance(p1, p2):
p1 = point_to_tuple(p1)
p2 = point_to_tuple(p2)
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5
# --- Funktion zum Splitten einer Zeichnung in mögliche Einzelformen (Bubbles) ---
def split_drawing_if_possible(drawing, threshold_dist=10):
"""
Teilt ein einzelnes Drawing-Objekt in kleinere Gruppen von Segmenten,
wenn innerhalb der Pfadpunkte großer Abstand ist.
Rückgabe: list von Zeichnungen (je dict mit mindestens 'items' und 'rect')
"""
items = drawing.get("items", [])
if not items:
return []
groups = []
current_group = []
last_end_point = None
for item in items:
item_type, *coords = item
if item_type in ('l','c','re'):
start_point = (coords[0], coords[1])
if last_end_point is not None:
dist = point_distance(start_point, last_end_point)
if dist > threshold_dist and current_group:
groups.append(current_group)
current_group = []
current_group.append(item)
last_end_point = (coords[-2], coords[-1])
else:
# Andere Items (z.B. move) einfach weitergeben
current_group.append(item)
if current_group:
groups.append(current_group)
splitted_drawings = []
for group in groups:
xs, ys = [], []
for item in group:
itype, *c = item
for i in range(0,len(c),2):
xs.append(c[i])
ys.append(c[i+1])
if not xs or not ys:
continue
bbox = (min(xs), min(ys), max(xs), max(ys))
splitted_drawings.append({
"items": group,
"rect": bbox,
"closed": drawing.get("closed", False)
})
return splitted_drawings
# --- Hauptfunktion ---
def process_pid_pdf_individual(pdf_filepath, output_csv_filepath):
"""
Identifiziert individuelle Instrumentenblasen,
extrahiert Text und speichert die Ergebnisse in einer CSV-Datei.
Integriert die Splitting-Logik für zusammenhängende Formen.
"""
try:
doc = fitz.open(pdf_filepath)
except Exception as e:
print(f"Error opening PDF file '{pdf_filepath}': {e}")
return
identified_bubbles = []
print(f"Processing PDF: {pdf_filepath}")
print("Phase 1: Identifying individual bubble candidates with splitting...")
for page_num in range(len(doc)):
page = doc[page_num]
drawings = page.get_drawings()
print(f"Page {page_num + 1}/{len(doc)}: Analyzing {len(drawings)} drawing objects.")
for drawing_index, drawing in enumerate(drawings):
# Splitte ggf. komplexe Zeichnungen (zusammenhängende Formen)
splitted = split_drawing_if_possible(drawing, threshold_dist=10)
if not splitted:
splitted = [drawing]
for split_index, d in enumerate(splitted):
items = d.get("items", [])
num_segments = len(items)
if not (min_segments <= num_segments <= max_segments):
continue
# Prüfe "geschlossen"-Flag
is_closed = d.get("closed", False)
if not is_closed and items:
first_point, last_point = None, None
for item_type, *coords in items:
if item_type in ('l', 'c', 're') and len(coords) >= 2:
if first_point is None:
first_point = (coords[0], coords[1])
last_point = (coords[-2], coords[-1])
if first_point and last_point and \
abs(first_point[0] - last_point[0]) < 1.0 and \
abs(first_point[1] - last_point[1]) < 1.0:
is_closed = True
# Wenn gewünscht, hier auskommentieren, um offene Pfade zu überspringen:
# if not is_closed: continue
bbox_obj = d.get("rect")
bbox = None
if bbox_obj:
bbox = tuple(bbox_obj) if not hasattr(bbox_obj, "x0") else (bbox_obj.x0, bbox_obj.y0, bbox_obj.x1, bbox_obj.y1)
if not bbox or bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
xs, ys = [], []
for item_type, *coords in items:
if len(coords) >= 2:
for i in range(0,len(coords),2):
if i+1 < len(coords) and isinstance(coords[i], (int,float)) and isinstance(coords[i+1], (int,float)):
xs.append(coords[i])
ys.append(coords[i+1])
if xs and ys:
bbox = (min(xs), min(ys), max(xs), max(ys))
else:
bbox = None
if bbox is None or bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
continue
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
if width <= 1 or height <= 1:
continue
area = width * height
aspect_ratio = width / height if height != 0 else 0
if not (min_area <= area <= max_area):
continue
if not (min_aspect <= aspect_ratio <= max_aspect):
continue
candidate_id = f"p{page_num+1}_d{drawing_index}_s{split_index}"
identified_bubbles.append({
"id": candidate_id,
"page": page_num + 1,
"bbox": bbox,
"segments": num_segments,
"area": area,
"aspect_ratio": aspect_ratio,
"text": ""
})
print(f"Phase 1 complete. Found {len(identified_bubbles)} potential bubble candidates after splitting.")
if not identified_bubbles:
print("No potential bubble candidates found. Versuch die Filterparameter anzupassen (area, aspect_ratio, segments).")
doc.close()
return
print("Phase 2: Extracting text for individual candidates...")
for bubble in identified_bubbles:
page_index = bubble["page"] - 1
page = doc[page_index]
try:
rect = fitz.Rect(bubble["bbox"])
rect.x0 -= text_extraction_expansion
rect.y0 -= text_extraction_expansion
rect.x1 += text_extraction_expansion
rect.y1 += text_extraction_expansion
text = page.get_text("text", clip=rect, sort=True).strip()
text = ' '.join(text.split()) # Whitespace säubern
bubble["text"] = text
except Exception as e:
print(f" Warning: Fehler beim Text extrahieren für Candidate {bubble['id']}: {e}")
bubble["text"] = ""
print("Phase 2 complete. Text extraction finished.")
print("Phase 3: Sorting final bubbles for consistent output.")
identified_bubbles.sort(key=lambda b: (b['page'], b['bbox'][1], b['bbox'][0]))
print(f"Phase 4: Writing {len(identified_bubbles)} individual bubbles to CSV: {output_csv_filepath}")
if identified_bubbles:
try:
with open(output_csv_filepath, "w", newline='', encoding="utf-8") as csvfile:
fieldnames = [
'page', 'x0', 'y0', 'x1', 'y1',
'text',
'area',
'aspect_ratio',
'segments'
]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for bubble in identified_bubbles:
x0, y0, x1, y1 = bubble["bbox"]
writer.writerow({
"page": bubble["page"],
"x0": f"{x0:.2f}", "y0": f"{y0:.2f}",
"x1": f"{x1:.2f}", "y1": f"{y1:.2f}",
"text": bubble["text"],
"area": f"{bubble['area']:.1f}",
"aspect_ratio": f"{bubble['aspect_ratio']:.2f}",
"segments": bubble["segments"]
})
print(f"Processing complete. Ergebnisse erfolgreich gespeichert in '{output_csv_filepath}'.")
except IOError as e:
print(f"Error writing to CSV file '{output_csv_filepath}': {e}")
except Exception as e:
print(f"Unexpected error during CSV writing: {e}")
else:
print("Keine finalen Blasen zum Schreiben in die CSV gefunden.")
doc.close()
print("PDF-Dokument geschlossen.")
# --- Script Execution ---
if __name__ == "__main__":
if os.path.exists(pdf_path):
process_pid_pdf_individual(pdf_path, csv_filename)
else:
print(f"Error: PDF file not found at specified path: {pdf_path}")
print("Bitte stelle sicher, dass die PDF-Datei existiert oder gib den korrekten Pfad an.")
Zusammenfassung der Änderung:
point_distance erwartet jetzt Tupel, konvertiert vor der Berechnung fitz.Point sicher und zuverlässig in (x, y) Tupel.
Im Splitcode werden Start- und Endpunkte als Tupel gespeichert, so dass der Abstand fehlerfrei berechnet werden kann.
Dadurch wird der gezeigte TypeError behoben.
Falls Du weitere Fragen hast oder Hilfe zur weiteren Anpassung möchtest, meld Dich gern!