working, images broken

This commit is contained in:
2025-06-23 04:08:45 -05:00
parent 2bb7a29141
commit 23fee50a77
7 changed files with 135 additions and 79 deletions

View File

@ -22,6 +22,8 @@ migrate = Migrate()
login_manager = LoginManager() login_manager = LoginManager()
csrf = CSRFProtect() csrf = CSRFProtect()
from plugins.media.routes import generate_image_url # Import it here
def create_app(): def create_app():
app = Flask(__name__) app = Flask(__name__)
@ -112,4 +114,6 @@ def create_app():
from datetime import datetime from datetime import datetime
return {'current_year': datetime.now().year} return {'current_year': datetime.now().year}
app.jinja_env.globals['generate_image_url'] = generate_image_url
return app return app

BIN
nip.zip

Binary file not shown.

View File

@ -1,7 +1,8 @@
# plugins/media/routes.py # plugins/media/routes.py
import os import os
from uuid import uuid4 import uuid
from werkzeug.utils import secure_filename
from datetime import datetime from datetime import datetime
from PIL import Image, ExifTags from PIL import Image, ExifTags
@ -73,48 +74,40 @@ def _strip_exif(image: Image.Image) -> Image.Image:
return image return image
def _process_upload_file( def _process_upload_file(file, uploader_id, plugin='', related_id=0, plant_id=None, growlog_id=None, caption=None):
file, """Handles saving an uploaded file and creating the Media record."""
uploader_id: int,
plugin: str,
related_id: int
):
"""
Save the uploaded image (strip EXIF), write Media row with
file_url, and return the Media instance.
"""
ext = os.path.splitext(file.filename)[1].lower()
if ext not in {".jpg", ".jpeg", ".png", ".gif", ".webp"}:
raise ValueError("Unsupported file type.")
# generate a stable filename # Generate a unique filename
filename = f"{uuid4().hex}{ext}"
# determine disk path
abs_dir, subdir = get_upload_path(plugin, related_id)
full_path = os.path.join(abs_dir, filename)
# strip EXIF and save
img = Image.open(file)
img = _strip_exif(img)
img.save(full_path)
# create the DB record
now = datetime.utcnow() now = datetime.utcnow()
media = Media( unique_id = str(uuid.uuid4()).replace("-", "")
uploader_id=uploader_id, secure_name = secure_filename(file.filename)
file_url=f"{subdir}/{filename}", filename = f"{unique_id}_{secure_name}"
uploaded_at=now
# Construct the save path
storage_path = os.path.join(
current_app.config['UPLOAD_FOLDER'],
str(uploader_id),
now.strftime('%Y/%m/%d')
) )
os.makedirs(storage_path, exist_ok=True)
# legacy relationships full_path = os.path.join(storage_path, filename)
if plugin == "plant": file.save(full_path)
media.plant_id = related_id
elif plugin == "growlog":
media.growlog_id = related_id
db.session.add(media) file_url = f"/{uploader_id}/{now.strftime('%Y/%m/%d')}/{filename}"
db.session.commit()
media = Media(
plugin=plugin,
related_id=related_id,
filename=filename,
uploaded_at=now,
uploader_id=uploader_id,
caption=caption,
plant_id=plant_id,
growlog_id=growlog_id,
created_at=now,
file_url=file_url
)
return media return media

View File

@ -101,14 +101,14 @@ class Plant(db.Model):
media_items = db.relationship( media_items = db.relationship(
'plugins.media.models.Media', 'plugins.media.models.Media',
back_populates='plant', back_populates='plant',
lazy='dynamic', lazy='select', # ← this is the fix
cascade='all, delete-orphan', cascade='all, delete-orphan',
foreign_keys='plugins.media.models.Media.plant_id' foreign_keys='plugins.media.models.Media.plant_id'
) )
@property @property
def media(self): def media(self):
return self.media_items.all() return self.media_items # already a list when lazy='select'
# the one you see on the detail page # the one you see on the detail page
featured_media = db.relationship( featured_media = db.relationship(

View File

@ -1,5 +1,7 @@
from uuid import uuid4 from uuid import uuid4
import os import os
from sqlalchemy.orm import joinedload
from flask import ( from flask import (
Blueprint, Blueprint,
render_template, render_template,
@ -10,6 +12,7 @@ from flask import (
current_app, current_app,
) )
from flask_login import login_required, current_user from flask_login import login_required, current_user
from app import db from app import db
from .models import Plant, PlantCommonName, PlantScientificName from .models import Plant, PlantCommonName, PlantScientificName
from .forms import PlantForm from .forms import PlantForm
@ -37,7 +40,9 @@ def inject_image_helper():
@login_required @login_required
def index(): def index():
plants = ( plants = (
Plant.query.filter_by(owner_id=current_user.id) Plant.query
.options(joinedload(Plant.media_items))
.filter_by(owner_id=current_user.id)
.order_by(Plant.id.desc()) .order_by(Plant.id.desc())
.all() .all()
) )

View File

@ -154,7 +154,13 @@
{% endif %} {% endif %}
<a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}"> <a href="{{ url_for('plant.detail', uuid_val=plant.uuid) }}">
<img src="{{ generate_image_url(featured) }}" {# pick featured → first media if no explicit featured #}
{% set featured = plant.featured_media %}
{% if not featured and plant.media %}
{% set featured = plant.media[0] %}
{% endif %}
<img
src="{{ generate_image_url(featured) }}"
class="card-img-top" class="card-img-top"
style="height:200px;object-fit:cover;" style="height:200px;object-fit:cover;"
alt="Image for {{ plant.common_name.name }}"> alt="Image for {{ plant.common_name.name }}">

View File

@ -9,6 +9,7 @@ import uuid
import zipfile import zipfile
import tempfile import tempfile
import difflib import difflib
import traceback
from datetime import datetime from datetime import datetime
# Thirdparty # Thirdparty
@ -80,7 +81,7 @@ def upload():
filename = file.filename.lower().strip() filename = file.filename.lower().strip()
# ── ZIP Import Flow ─────────────────────────────────────────────────── # ── ZIP Import Flow ────────────────────────────────────────────────
if filename.endswith(".zip"): if filename.endswith(".zip"):
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip") tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
file.save(tmp_zip.name) file.save(tmp_zip.name)
@ -127,6 +128,7 @@ def upload():
tmpdir = tempfile.mkdtemp() tmpdir = tempfile.mkdtemp()
z.extractall(tmpdir) z.extractall(tmpdir)
# --- load and validate plants.csv ---
plant_path = os.path.join(tmpdir, "plants.csv") plant_path = os.path.join(tmpdir, "plants.csv")
with open(plant_path, newline="", encoding="utf-8-sig") as pf: with open(plant_path, newline="", encoding="utf-8-sig") as pf:
reader = csv.DictReader(pf) reader = csv.DictReader(pf)
@ -138,6 +140,7 @@ def upload():
return redirect(request.url) return redirect(request.url)
plant_rows = list(reader) plant_rows = list(reader)
# --- load and validate media.csv ---
media_path = os.path.join(tmpdir, "media.csv") media_path = os.path.join(tmpdir, "media.csv")
with open(media_path, newline="", encoding="utf-8-sig") as mf: with open(media_path, newline="", encoding="utf-8-sig") as mf:
mreader = csv.DictReader(mf) mreader = csv.DictReader(mf)
@ -149,10 +152,10 @@ def upload():
return redirect(request.url) return redirect(request.url)
media_rows = list(mreader) media_rows = list(mreader)
# --- import plants ---
neo = get_neo4j_handler() neo = get_neo4j_handler()
added_plants = 0 added_plants = 0
plant_map = {} plant_map = {}
for row in plant_rows: for row in plant_rows:
common = PlantCommonName.query.filter_by(name=row["Name"]).first() common = PlantCommonName.query.filter_by(name=row["Name"]).first()
if not common: if not common:
@ -192,11 +195,14 @@ def upload():
neo.create_plant_node(p.uuid, row["Name"]) neo.create_plant_node(p.uuid, row["Name"])
if row.get("Mother UUID"): if row.get("Mother UUID"):
neo.create_lineage(child_uuid=p.uuid, parent_uuid=row["Mother UUID"]) neo.create_lineage(
child_uuid=p.uuid,
parent_uuid=row["Mother UUID"]
)
added_plants += 1 added_plants += 1
# ✅ Import media once for the full batch # --- import media (FIX: now passing plant_id) ---
added_media = 0 added_media = 0
for mrow in media_rows: for mrow in media_rows:
plant_uuid = mrow["Plant UUID"] plant_uuid = mrow["Plant UUID"]
@ -220,14 +226,18 @@ def upload():
file=file_storage, file=file_storage,
uploader_id=current_user.id, uploader_id=current_user.id,
plugin="plant", plugin="plant",
related_id=plant_id related_id=plant_id,
plant_id=plant_id # ← ensure the FK is set!
) )
media.uploaded_at = datetime.fromisoformat(mrow["Uploaded At"]) media.uploaded_at = datetime.fromisoformat(mrow["Uploaded At"])
media.caption = mrow["Source Type"] media.caption = mrow["Source Type"]
db.session.add(media) db.session.add(media)
added_media += 1 added_media += 1
except Exception as e: except Exception as e:
current_app.logger.warning(f"Failed to import media file: {subpath}{e}") current_app.logger.warning(
f"Failed to import media file: {subpath}{e}"
)
current_app.logger.debug(traceback.format_exc())
db.session.commit() db.session.commit()
neo.close() neo.close()
@ -236,7 +246,7 @@ def upload():
flash(f"Imported {added_plants} plants and {added_media} images.", "success") flash(f"Imported {added_plants} plants and {added_media} images.", "success")
return redirect(request.url) return redirect(request.url)
# ── Standalone CSV Review Flow ───────────────────────────────────── # ── CSV Review Flow ─────────────────────────────────────────────────
if filename.endswith(".csv"): if filename.endswith(".csv"):
try: try:
stream = io.StringIO(file.stream.read().decode("utf-8-sig")) stream = io.StringIO(file.stream.read().decode("utf-8-sig"))
@ -258,15 +268,11 @@ def upload():
all_sci = {s.name.lower(): s for s in PlantScientificName.query.all()} all_sci = {s.name.lower(): s for s in PlantScientificName.query.all()}
for row in reader: for row in reader:
uuid_raw = row.get("uuid", "") uuid_val = row.get("uuid", "").strip().strip('"')
uuid_val = uuid_raw.strip().strip('"') name = row.get("name", "").strip()
name_raw = row.get("name", "") sci_name = row.get("scientific_name", "").strip()
name = name_raw.strip()
sci_raw = row.get("scientific_name", "")
sci_name = sci_raw.strip()
plant_type = row.get("plant_type", "").strip() or "plant" plant_type = row.get("plant_type", "").strip() or "plant"
mother_raw = row.get("mother_uuid", "") mother_uuid= row.get("mother_uuid", "").strip().strip('"')
mother_uuid = mother_raw.strip().strip('"')
if not (uuid_val and name and plant_type): if not (uuid_val and name and plant_type):
continue continue
@ -274,11 +280,14 @@ def upload():
suggestions = difflib.get_close_matches( suggestions = difflib.get_close_matches(
sci_name.lower(), sci_name.lower(),
list(all_sci.keys()), list(all_sci.keys()),
n=1, cutoff=0.8 n=1,
cutoff=0.8
) )
suggested = (all_sci[suggestions[0]].name suggested = (
all_sci[suggestions[0]].name
if suggestions and suggestions[0] != sci_name.lower() if suggestions and suggestions[0] != sci_name.lower()
else None) else None
)
item = { item = {
"uuid": uuid_val, "uuid": uuid_val,
@ -294,7 +303,44 @@ def upload():
session["review_list"] = review_list session["review_list"] = review_list
return redirect(url_for("utility.review")) return redirect(url_for("utility.review"))
flash("Unsupported file type. Please upload a ZIP or CSV.", "danger") # ── Direct Media Upload Flow ───────────────────────────────────────
plugin = request.form.get("plugin", '')
related_id = request.form.get("related_id", 0)
plant_id = request.form.get("plant_id", None)
growlog_id = request.form.get("growlog_id", None)
caption = request.form.get("caption", None)
now = datetime.utcnow()
unique_id = str(uuid.uuid4()).replace("-", "")
secure_name= secure_filename(file.filename)
storage_path = os.path.join(
current_app.config['UPLOAD_FOLDER'],
str(current_user.id),
now.strftime('%Y/%m/%d')
)
os.makedirs(storage_path, exist_ok=True)
full_file_path = os.path.join(storage_path, f"{unique_id}_{secure_name}")
file.save(full_file_path)
file_url = f"/{current_user.id}/{now.strftime('%Y/%m/%d')}/{unique_id}_{secure_name}"
media = Media(
plugin=plugin,
related_id=related_id,
filename=f"{unique_id}_{secure_name}",
uploaded_at=now,
uploader_id=current_user.id,
caption=caption,
plant_id=plant_id,
growlog_id=growlog_id,
created_at=now,
file_url=file_url
)
db.session.add(media)
db.session.commit()
flash("File uploaded and saved successfully.", "success")
return redirect(request.url) return redirect(request.url)
return render_template("utility/upload.html", csrf_token=generate_csrf()) return render_template("utility/upload.html", csrf_token=generate_csrf())
@ -419,10 +465,12 @@ def export_data():
plants_csv = plant_io.getvalue() plants_csv = plant_io.getvalue()
# 2) Gather media # 2) Gather media
media_records = (Media.query media_records = (
.filter_by(uploader_id=current_user.id) Media.query
.filter(Media.uploader_id == current_user.id, Media.plant_id.isnot(None))
.order_by(Media.id) .order_by(Media.id)
.all()) .all()
)
# Build media.csv # Build media.csv
media_io = io.StringIO() media_io = io.StringIO()
mw = csv.writer(media_io) mw = csv.writer(media_io)