-
Notifications
You must be signed in to change notification settings - Fork 0
story/HOP-60 #48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
story/HOP-60 #48
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
33f9323
[HOP-60] Created admin workflow for adding zip file, csv, templates -…
Girik1105 4fb2e0a
[HOP-60] Mac support
Girik1105 5455b38
Merge branch 'develop' into story/HOP-60
Girik1105 a909add
[HOP-60] Resolved merge conflicts
Girik1105 147ffb8
[HOP-60] increased timeout added retry upload functionality, better e…
Girik1105 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,17 @@ | ||
| import csv | ||
| import io | ||
| import logging | ||
| import os | ||
| import zipfile | ||
|
|
||
| from django.contrib import admin | ||
| from django.contrib import admin, messages | ||
| from django.contrib.auth.admin import UserAdmin | ||
| from django.contrib.auth.models import User | ||
| from django.core.files.base import ContentFile | ||
| from django.http import HttpResponseRedirect | ||
| from django.shortcuts import render | ||
| from django.urls import path, reverse | ||
|
|
||
| from ask.models import Conversation, TermsAcceptance, QARecord, SimWorkflow, WebsiteResource, PDFResource | ||
| from ask.kb_connector import add_website_to_kb, add_pdf_to_kb, delete_kb_document | ||
|
|
||
|
|
@@ -250,3 +259,115 @@ def save_model(self, request, obj, form, change): | |
| logger.exception("Failed to send PDF to KB: %s", obj.file.name) | ||
| self.message_user(request, f"PDF saved but failed to send to Knowledge Base: {e}", level="warning") | ||
|
|
||
| def get_urls(self): | ||
| urls = super().get_urls() | ||
| custom = [ | ||
| path( | ||
| "upload-zip/", | ||
| self.admin_site.admin_view(self.zip_upload_view), | ||
| name="ask_pdfresource_upload_zip", | ||
| ), | ||
| ] | ||
| return custom + urls | ||
|
|
||
| def zip_upload_view(self, request): | ||
| changelist_url = reverse("admin:ask_pdfresource_changelist") | ||
|
|
||
| if request.method == "POST": | ||
| zip_file = request.FILES.get("zip_file") | ||
| if not zip_file: | ||
| messages.error(request, "Please select a zip file to upload.") | ||
| return HttpResponseRedirect(request.path) | ||
|
|
||
| try: | ||
| archive = zipfile.ZipFile(zip_file) | ||
| except zipfile.BadZipFile: | ||
| messages.error(request, "The uploaded file is not a valid zip archive.") | ||
| return HttpResponseRedirect(request.path) | ||
|
|
||
| with archive: | ||
| # skip macOS Finder metadata: __MACOSX/ dir and AppleDouble "._" twins | ||
| def _is_real(name): | ||
| base = os.path.basename(name) | ||
| return not name.startswith("__MACOSX/") and not base.startswith("._") and base != "" | ||
|
|
||
| real_names = [n for n in archive.namelist() if _is_real(n)] | ||
|
|
||
| csv_names = [n for n in real_names if n.lower().endswith(".csv")] | ||
| if len(csv_names) == 0: | ||
| messages.error(request, "Zip must contain one CSV metadata file (filename,title).") | ||
| return HttpResponseRedirect(request.path) | ||
| if len(csv_names) > 1: | ||
| messages.error(request, f"Zip must contain exactly one CSV; found {len(csv_names)}.") | ||
| return HttpResponseRedirect(request.path) | ||
|
|
||
| csv_text = archive.read(csv_names[0]).decode("utf-8-sig") | ||
| reader = csv.DictReader(io.StringIO(csv_text)) | ||
| required = {"filename", "title"} | ||
| if not required.issubset({(h or "").strip() for h in (reader.fieldnames or [])}): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| messages.error(request, "CSV must have 'filename' and 'title' columns.") | ||
| return HttpResponseRedirect(request.path) | ||
|
|
||
| zip_members = {n: n for n in real_names} | ||
| # also index by basename so CSV can refer to bare filenames regardless of zip layout | ||
| for n in real_names: | ||
| zip_members.setdefault(os.path.basename(n), n) | ||
|
|
||
| total = 0 | ||
| saved = 0 | ||
| kb_pushed = 0 | ||
| kb_failed = 0 | ||
| for row in reader: | ||
| total += 1 | ||
| filename = (row.get("filename") or "").strip() | ||
| title = (row.get("title") or "").strip() | ||
| if not filename or not title: | ||
| messages.warning(request, f"Row {total}: missing filename or title; skipped.") | ||
| continue | ||
|
|
||
| member = zip_members.get(filename) or zip_members.get(os.path.basename(filename)) | ||
| if not member: | ||
| messages.warning(request, f"Row {total}: '{filename}' not in zip; skipped.") | ||
| continue | ||
|
|
||
| try: | ||
| pdf_bytes = archive.read(member) | ||
| except KeyError: | ||
| messages.warning(request, f"Row {total}: could not read '{filename}'; skipped.") | ||
| continue | ||
|
|
||
| obj = PDFResource(title=title, creator=request.user, modifier=request.user) | ||
| obj.file.save(os.path.basename(filename), ContentFile(pdf_bytes), save=True) | ||
| saved += 1 | ||
|
|
||
| try: | ||
| result = add_pdf_to_kb(pdf_bytes, os.path.basename(filename), title) | ||
| obj.mcp_kb_document_id = result.get("doc_id") | ||
| obj.save(update_fields=["mcp_kb_document_id"]) | ||
| kb_pushed += 1 | ||
| except Exception as e: | ||
| logger.exception("Bulk: failed to send PDF to KB: %s", filename) | ||
| messages.warning(request, f"Row {total}: '{title}' saved but KB push failed: {e}") | ||
| kb_failed += 1 | ||
|
|
||
| if kb_failed: | ||
| messages.warning( | ||
| request, | ||
| f"Saved {saved} of {total} PDFs; {kb_pushed} pushed to Knowledge Base, " | ||
| f"{kb_failed} failed KB push (PDFs are stored locally but not searchable).", | ||
| ) | ||
| else: | ||
| messages.success(request, f"Imported {saved} of {total} PDFs.") | ||
| return HttpResponseRedirect(changelist_url) | ||
|
|
||
| return render( | ||
| request, | ||
| "admin/ask/pdfresource/upload_zip.html", | ||
| { | ||
| **self.admin_site.each_context(request), | ||
| "opts": self.model._meta, | ||
| "title": "Upload zip of PDFs", | ||
| "changelist_url": changelist_url, | ||
| }, | ||
| ) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 8 additions & 0 deletions
8
hospexplorer/ask/templates/admin/ask/pdfresource/change_list.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| {% extends "admin/change_list.html" %} | ||
|
|
||
| {% block object-tools-items %} | ||
| <li> | ||
| <a href="upload-zip/" class="addlink">Upload zip of PDFs</a> | ||
| </li> | ||
| {{ block.super }} | ||
| {% endblock %} |
30 changes: 30 additions & 0 deletions
30
hospexplorer/ask/templates/admin/ask/pdfresource/upload_zip.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| {% extends "admin/base_site.html" %} | ||
|
|
||
| {% block breadcrumbs %} | ||
| <div class="breadcrumbs"> | ||
| <a href="{% url 'admin:index' %}">Home</a> | ||
| › <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a> | ||
| › <a href="{{ changelist_url }}">{{ opts.verbose_name_plural|capfirst }}</a> | ||
| › {{ title }} | ||
| </div> | ||
| {% endblock %} | ||
|
|
||
| {% block content %} | ||
| <h1>{{ title }}</h1> | ||
| <p> | ||
| Upload a <code>.zip</code> containing PDF files and a single CSV metadata file | ||
| with columns <code>filename,title</code>. Each row creates a PDF Resource | ||
| and pushes the file to the Knowledge Base. | ||
| </p> | ||
| <form method="post" enctype="multipart/form-data"> | ||
| {% csrf_token %} | ||
| <p> | ||
| <label for="zip_file">Zip file:</label> | ||
| <input type="file" name="zip_file" id="zip_file" accept=".zip" required> | ||
| </p> | ||
| <div class="submit-row"> | ||
| <input type="submit" value="Upload" class="default"> | ||
| <a href="{{ changelist_url }}" class="button cancel-link">Cancel</a> | ||
| </div> | ||
| </form> | ||
| {% endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
those should probably be configurable