working, images broken
This commit is contained in:
@ -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__)
|
||||||
@ -111,5 +113,7 @@ def create_app():
|
|||||||
def inject_current_year():
|
def inject_current_year():
|
||||||
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
|
||||||
|
@ -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
|
||||||
|
|
||||||
|
|
||||||
|
@ -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(
|
||||||
|
@ -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()
|
||||||
)
|
)
|
||||||
|
@ -154,10 +154,16 @@
|
|||||||
{% 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 #}
|
||||||
class="card-img-top"
|
{% set featured = plant.featured_media %}
|
||||||
style="height:200px;object-fit:cover;"
|
{% if not featured and plant.media %}
|
||||||
alt="Image for {{ plant.common_name.name }}">
|
{% set featured = plant.media[0] %}
|
||||||
|
{% endif %}
|
||||||
|
<img
|
||||||
|
src="{{ generate_image_url(featured) }}"
|
||||||
|
class="card-img-top"
|
||||||
|
style="height:200px;object-fit:cover;"
|
||||||
|
alt="Image for {{ plant.common_name.name }}">
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
<div class="card-body d-flex flex-column">
|
<div class="card-body d-flex flex-column">
|
||||||
|
@ -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
|
||||||
|
|
||||||
# Third‐party
|
# Third‐party
|
||||||
@ -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,32 +128,34 @@ 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)
|
||||||
if reader.fieldnames != PLANT_HEADERS:
|
if reader.fieldnames != PLANT_HEADERS:
|
||||||
missing = set(PLANT_HEADERS) - set(reader.fieldnames or [])
|
missing = set(PLANT_HEADERS) - set(reader.fieldnames or [])
|
||||||
extra = set(reader.fieldnames or []) - set(PLANT_HEADERS)
|
extra = set(reader.fieldnames or []) - set(PLANT_HEADERS)
|
||||||
os.remove(tmp_zip.name)
|
os.remove(tmp_zip.name)
|
||||||
flash(f"plants.csv header mismatch. Missing: {missing}, Extra: {extra}", "danger")
|
flash(f"plants.csv header mismatch. Missing: {missing}, Extra: {extra}", "danger")
|
||||||
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)
|
||||||
if mreader.fieldnames != MEDIA_HEADERS:
|
if mreader.fieldnames != MEDIA_HEADERS:
|
||||||
missing = set(MEDIA_HEADERS) - set(mreader.fieldnames or [])
|
missing = set(MEDIA_HEADERS) - set(mreader.fieldnames or [])
|
||||||
extra = set(mreader.fieldnames or []) - set(MEDIA_HEADERS)
|
extra = set(mreader.fieldnames or []) - set(MEDIA_HEADERS)
|
||||||
os.remove(tmp_zip.name)
|
os.remove(tmp_zip.name)
|
||||||
flash(f"media.csv header mismatch. Missing: {missing}, Extra: {extra}", "danger")
|
flash(f"media.csv header mismatch. Missing: {missing}, Extra: {extra}", "danger")
|
||||||
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,20 +195,23 @@ 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"]
|
||||||
plant_id = plant_map.get(plant_uuid)
|
plant_id = plant_map.get(plant_uuid)
|
||||||
if not plant_id:
|
if not plant_id:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
subpath = mrow["Image Path"].split('uploads/', 1)[-1]
|
subpath = mrow["Image Path"].split('uploads/', 1)[-1]
|
||||||
src = os.path.join(tmpdir, "images", subpath)
|
src = os.path.join(tmpdir, "images", subpath)
|
||||||
if not os.path.isfile(src):
|
if not os.path.isfile(src):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@ -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"))
|
||||||
@ -255,18 +265,14 @@ def upload():
|
|||||||
review_list = []
|
review_list = []
|
||||||
|
|
||||||
all_common = {c.name.lower(): c for c in PlantCommonName.query.all()}
|
all_common = {c.name.lower(): c for c in PlantCommonName.query.all()}
|
||||||
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,17 +280,20 @@ 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
|
||||||
|
if suggestions and suggestions[0] != sci_name.lower()
|
||||||
|
else None
|
||||||
)
|
)
|
||||||
suggested = (all_sci[suggestions[0]].name
|
|
||||||
if suggestions and suggestions[0] != sci_name.lower()
|
|
||||||
else None)
|
|
||||||
|
|
||||||
item = {
|
item = {
|
||||||
"uuid": uuid_val,
|
"uuid": uuid_val,
|
||||||
"name": name,
|
"name": name,
|
||||||
"sci_name": sci_name,
|
"sci_name": sci_name,
|
||||||
"suggested": suggested,
|
"suggested": suggested,
|
||||||
"plant_type": plant_type,
|
"plant_type": plant_type,
|
||||||
"mother_uuid": mother_uuid
|
"mother_uuid": mother_uuid
|
||||||
}
|
}
|
||||||
@ -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
|
||||||
.order_by(Media.id)
|
.filter(Media.uploader_id == current_user.id, Media.plant_id.isnot(None))
|
||||||
.all())
|
.order_by(Media.id)
|
||||||
|
.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)
|
||||||
|
Reference in New Issue
Block a user