|
| 1 | +# functions_chat_upload_extraction.py |
| 2 | +"""Describe what ingestion extracted from the workspace document behind a chat upload. |
| 3 | +
|
| 4 | +A file uploaded into a conversation is stored as a workspace document, so the chat message |
| 5 | +itself carries no text. Opening the upload therefore has to read what ingestion produced for |
| 6 | +that document: the indexed text that search and chat actually use, and the structured image |
| 7 | +analysis that was saved on the document record but was never shown anywhere. |
| 8 | +
|
| 9 | +Everything here is pure so the route can stay thin and the shaping can be tested without |
| 10 | +Cosmos DB, AI Search, or Azure credentials. |
| 11 | +""" |
| 12 | + |
| 13 | +WORKSPACE_UPLOAD_FILE_CONTENT_SOURCE = "workspace" |
| 14 | +NO_EXTRACTED_CONTENT_MESSAGE = "No extracted content is available for this file yet." |
| 15 | +STILL_PROCESSING_MESSAGE = "This file is still being processed. Try again when it finishes." |
| 16 | +PROCESSING_FAILED_MESSAGE = ( |
| 17 | + "Processing this file failed, so nothing was extracted. Reprocess or re-upload it to try again." |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +def _clean_text(value): |
| 22 | + return value.strip() if isinstance(value, str) else "" |
| 23 | + |
| 24 | + |
| 25 | +def _clean_list(values): |
| 26 | + if isinstance(values, str): |
| 27 | + values = [values] |
| 28 | + if not isinstance(values, (list, tuple)): |
| 29 | + return [] |
| 30 | + return [value.strip() for value in values if isinstance(value, str) and value.strip()] |
| 31 | + |
| 32 | + |
| 33 | +def summarize_vision_analysis(vision_analysis): |
| 34 | + """Return the displayable parts of a stored vision analysis, or None when it has none. |
| 35 | +
|
| 36 | + An analysis that records an error is excluded, because its description is the error |
| 37 | + message rather than anything the model saw in the image. |
| 38 | + """ |
| 39 | + if not isinstance(vision_analysis, dict) or vision_analysis.get("error"): |
| 40 | + return None |
| 41 | + |
| 42 | + summary = { |
| 43 | + "model": _clean_text(vision_analysis.get("model") or vision_analysis.get("model_name")), |
| 44 | + "description": _clean_text(vision_analysis.get("description")), |
| 45 | + "objects": _clean_list(vision_analysis.get("objects")), |
| 46 | + "text": _clean_text(vision_analysis.get("text")), |
| 47 | + "analysis": _clean_text( |
| 48 | + vision_analysis.get("analysis") or vision_analysis.get("contextual_analysis") |
| 49 | + ), |
| 50 | + } |
| 51 | + if not any(summary[key] for key in ("description", "objects", "text", "analysis")): |
| 52 | + return None |
| 53 | + return summary |
| 54 | + |
| 55 | + |
| 56 | +def render_vision_analysis_text(summary): |
| 57 | + """Plain-text rendering for clients that can only show a text body.""" |
| 58 | + if not summary: |
| 59 | + return "" |
| 60 | + |
| 61 | + lines = ["AI Vision Analysis"] |
| 62 | + if summary.get("model"): |
| 63 | + lines.append(f"Model: {summary['model']}") |
| 64 | + if summary.get("description"): |
| 65 | + lines.append(f"\nDescription: {summary['description']}") |
| 66 | + if summary.get("objects"): |
| 67 | + lines.append(f"\nObjects Detected: {', '.join(summary['objects'])}") |
| 68 | + if summary.get("text"): |
| 69 | + lines.append(f"\nVisible Text: {summary['text']}") |
| 70 | + if summary.get("analysis"): |
| 71 | + lines.append(f"\nContextual Analysis: {summary['analysis']}") |
| 72 | + return "\n".join(lines).strip() |
| 73 | + |
| 74 | + |
| 75 | +def join_indexed_chunk_text(chunks): |
| 76 | + """Join the indexed text of ordered chunks, skipping empty ones.""" |
| 77 | + parts = [] |
| 78 | + for chunk in chunks or []: |
| 79 | + if not isinstance(chunk, dict): |
| 80 | + continue |
| 81 | + text = _clean_text(chunk.get("chunk_text")) |
| 82 | + if text: |
| 83 | + parts.append(text) |
| 84 | + return "\n\n".join(parts) |
| 85 | + |
| 86 | + |
| 87 | +def _percentage_complete(document): |
| 88 | + try: |
| 89 | + return int(document.get("percentage_complete")) |
| 90 | + except (TypeError, ValueError): |
| 91 | + return None |
| 92 | + |
| 93 | + |
| 94 | +def is_workspace_upload_failed(document): |
| 95 | + """Return whether ingestion stopped with an error, which is final rather than in progress.""" |
| 96 | + return _clean_text(document.get("status")).lower().startswith("error") |
| 97 | + |
| 98 | + |
| 99 | +def is_workspace_upload_processing(document): |
| 100 | + """Return whether the linked document has not finished ingestion yet.""" |
| 101 | + if is_workspace_upload_failed(document): |
| 102 | + return False |
| 103 | + percentage = _percentage_complete(document) |
| 104 | + if percentage is not None: |
| 105 | + return percentage < 100 |
| 106 | + status = _clean_text(document.get("status")).lower() |
| 107 | + return bool(status) and not status.startswith("processing complete") |
| 108 | + |
| 109 | + |
| 110 | +def build_workspace_upload_details(document, indexed_chunk_count): |
| 111 | + """Return the browser-safe extraction details of the document behind a chat upload. |
| 112 | +
|
| 113 | + Only descriptive ingestion results are returned. Storage locations, scope identifiers and |
| 114 | + anything the screening subsystem manages stay on the server. |
| 115 | + """ |
| 116 | + source = document if isinstance(document, dict) else {} |
| 117 | + try: |
| 118 | + number_of_pages = int(source.get("number_of_pages")) |
| 119 | + except (TypeError, ValueError): |
| 120 | + number_of_pages = None |
| 121 | + |
| 122 | + return { |
| 123 | + "document_id": _clean_text(source.get("id")), |
| 124 | + "title": _clean_text(source.get("title")), |
| 125 | + "abstract": _clean_text(source.get("abstract")), |
| 126 | + "keywords": _clean_list(source.get("keywords")), |
| 127 | + "status": _clean_text(source.get("status")), |
| 128 | + "percentage_complete": _percentage_complete(source), |
| 129 | + "number_of_pages": number_of_pages, |
| 130 | + "extraction_engine": _clean_text(source.get("extraction_engine")), |
| 131 | + "extraction_engine_reason": _clean_text(source.get("extraction_engine_reason")), |
| 132 | + "indexed_chunk_count": max(0, int(indexed_chunk_count or 0)), |
| 133 | + "vision_analysis": summarize_vision_analysis(source.get("vision_analysis")), |
| 134 | + } |
| 135 | + |
| 136 | + |
| 137 | +def build_workspace_upload_file_content(filename, document, chunks): |
| 138 | + """Shape the file-content response for a chat upload backed by a workspace document. |
| 139 | +
|
| 140 | + Returns ``(payload, status_code)``. ``file_content`` is always a readable body when the |
| 141 | + response succeeds, so a client that only renders text still has something to show: the |
| 142 | + indexed text when ingestion saved any, otherwise the stored image analysis. |
| 143 | + """ |
| 144 | + ordered_chunks = [chunk for chunk in chunks or [] if isinstance(chunk, dict)] |
| 145 | + indexed_text = join_indexed_chunk_text(ordered_chunks) |
| 146 | + details = build_workspace_upload_details(document, len(ordered_chunks)) |
| 147 | + body = indexed_text or render_vision_analysis_text(details["vision_analysis"]) |
| 148 | + |
| 149 | + if not body: |
| 150 | + source = document if isinstance(document, dict) else {} |
| 151 | + if is_workspace_upload_failed(source): |
| 152 | + message = PROCESSING_FAILED_MESSAGE |
| 153 | + elif is_workspace_upload_processing(source): |
| 154 | + message = STILL_PROCESSING_MESSAGE |
| 155 | + else: |
| 156 | + message = NO_EXTRACTED_CONTENT_MESSAGE |
| 157 | + return {"error": message, "workspace_document": details}, 404 |
| 158 | + |
| 159 | + return { |
| 160 | + "file_content": body, |
| 161 | + "filename": filename, |
| 162 | + "is_table": False, |
| 163 | + "file_content_source": WORKSPACE_UPLOAD_FILE_CONTENT_SOURCE, |
| 164 | + "indexed_text_available": bool(indexed_text), |
| 165 | + "workspace_document": details, |
| 166 | + }, 200 |
0 commit comments