Spaces:
Running on Zero
Running on Zero
fix(parser): support pre-extracted text streams for docx and pdf from MCP
Browse filesFiles changed (5)
359 unmodified lines360361362363364365359 unmodified linestry:ok, raw_text, cleaned_text, file_hash, err = parser.parse_file(temp_path)if not ok or not (cleaned_text or raw_text):return JSONResponse(status_code=400,359 unmodified lines360361362363364365366367368369370371372373374375376377378379359 unmodified linestry:ok, raw_text, cleaned_text, file_hash, err = parser.parse_file(temp_path)if not ok or not (cleaned_text or raw_text):# Check if content is already pre-extracted text (e.g. from MCP read_file tool)try:decoded = content.decode("utf-8", errors="ignore")if decoded and len(decoded.strip()) > 20:import ftfyfrom app.utils.text_cleaner import clean_textraw_text = ftfy.fix_text(decoded)cleaned_text = clean_text(raw_text)file_hash = hashlib.sha256(content).hexdigest()ok = Trueexcept Exception:passif not ok or not (cleaned_text or raw_text):return JSONResponse(status_code=400,
80 unmodified lines8182838480 unmodified linesreturn True, raw_text, cleaned_text, file_hash, Noneexcept Exception as e:return False, None, None, None, f"Parsing exception: {str(e)}"80 unmodified lines818283848586878889909192939480 unmodified linesreturn True, raw_text, cleaned_text, file_hash, Noneexcept Exception as e:# Fallback for documents that contain pre-extracted plain text (e.g. from MCP read_file or text streams)try:with open(path, "r", encoding="utf-8", errors="ignore") as f:fallback_text = f.read()if fallback_text and len(fallback_text.strip()) > 20:raw_text = ftfy.fix_text(fallback_text)cleaned_text = clean_text(raw_text)return True, raw_text, cleaned_text, file_hash, Noneexcept Exception:passreturn False, None, None, None, f"Parsing exception: {str(e)}"
26 unmodified lines2728293031323334353637383926 unmodified linesif suffix not in (".pdf", ".docx", ".txt"):return False, f"Unsupported file extension: {suffix}. Supported: .pdf, .docx, .txt"# Check magic bytestry:with open(path, "rb") as f:header = f.read(8)if suffix == ".pdf" and not header.startswith(b"%PDF"):return False, "Invalid PDF header signature (corrupted or renamed file)"elif suffix == ".docx" and not header.startswith(b"PK\x03\x04"):return False, "Invalid DOCX header signature (not a valid zip package)"except Exception as e:return False, f"Error reading file header: {str(e)}"26 unmodified lines27282930313233343536373839404142434445464748495051525326 unmodified linesif suffix not in (".pdf", ".docx", ".txt"):return False, f"Unsupported file extension: {suffix}. Supported: .pdf, .docx, .txt"# Check magic bytes (with safe fallback for pre-extracted text streams from MCP read_file)try:with open(path, "rb") as f:header = f.read(8)if suffix == ".pdf" and not header.startswith(b"%PDF"):try:with open(path, "r", encoding="utf-8", errors="strict") as tf:first_chars = tf.read(100)if len(first_chars.strip()) > 10:return True, ""except Exception:passreturn False, "Invalid PDF header signature (corrupted or renamed file)"elif suffix == ".docx" and not header.startswith(b"PK\x03\x04"):try:with open(path, "r", encoding="utf-8", errors="strict") as tf:first_chars = tf.read(100)if len(first_chars.strip()) > 10:return True, ""except Exception:passreturn False, "Invalid DOCX header signature (not a valid zip package)"except Exception as e:return False, f"Error reading file header: {str(e)}"
123455 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""Diagnostic Script to test specific Canada 🍁 and Repository folder pathsagainst the live Resource MCP Server (https://mcp-resource.onrender.com/mcp)."""5 unmodified linesMCP_URL = "https://mcp-resource.onrender.com/mcp"CALLBACK_PORT = 8765# Specific target paths from Microsoft Teams channelTARGET_PATHS = ["Repository","Repository/AI Engineer","Repository/.Net Developer","Repository/AWS","Repository/Azure","Repository/Business Analyst","Canada 🍁/Repository","Canada/Repository","Canada opportunity JD","Capgemini",]async def main():print("=" * 70)print("Testing Canada 🍁 & Repository Paths on Live Resource MCP")print(f"MCP URL: {MCP_URL}")print(f"Callback Port: {CALLBACK_PORT}")print("=" * 70)auth = OAuth(mcp_url=MCP_URL, client_name="ATS App", callback_port=CALLBACK_PORT)async with Client(MCP_URL, auth=auth) as client:print("\n[Step 1] Verifying signed-in account identity...")who = await client.call_tool("whoami")who_data = who.data if hasattr(who, "data") else whoprint(f"Logged in as: {who_data}")print("\n[Step 2] Testing specific folder paths with 'list_folder'...")discovered_files = []for folder_path in TARGET_PATHS:print(f"\n--- Testing Path: '{folder_path}' ---")try:res = await client.call_tool("list_folder", {"path": folder_path})data = res.data if hasattr(res, "data") else resif isinstance(data, str):if "error" in data.lower() or "did not allow" in data.lower():print(f" [SharePoint Access Denied] {data}")continuetry:data = json.loads(data)except Exception:print(f" [Response String] {data}")continueitems = data.get("items", []) if isinstance(data, dict) else (data if isinstance(data, list) else [])print(f" [SUCCESS] Found {len(items)} items in '{folder_path}':")for it in items[:6]:item_name = it.get("name") or it.get("path")item_type = it.get("type", "file")print(f" - [{item_type}] {item_name}")if item_type == "file":discovered_files.append(it.get("path") or item_name)except Exception as e:print(f" [Failed] {e}")# Test read_file if any file was discoveredprint("\n[Step 3] Testing 'read_file' tool...")test_file = discovered_files[0] if discovered_files else "Repository/AI Engineer/Arjun_Mehta_Lead_AI_Engineer.txt"print(f"Attempting to read file: '{test_file}'")try:read_res = await client.call_tool("read_file", {"path": test_file,"start_char": 0,"max_chars": 500,})read_data = read_res.data if hasattr(read_res, "data") else read_resif isinstance(read_data, dict):content = read_data.get("text") or read_data.get("content") or ""print(f" [SUCCESS] Read {len(content)} characters:")print(f" Preview: {content[:200]}...")else:print(f" [Result] {str(read_data)[:200]}")except Exception as e:print(f" [read_file Note] {e}")print("\n" + "=" * 70)print("Verification Completed!")print("=" * 70)if __name__ == "__main__":asyncio.run(main())123455 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Diagnostic script to inspect account identity, permissions, and test search_filesagainst the live Resource MCP Server (https://mcp-resource.onrender.com/mcp)."""5 unmodified linesMCP_URL = "https://mcp-resource.onrender.com/mcp"CALLBACK_PORT = 8765async def main():print("=" * 70)print("SharePoint Access Diagnostic Tool")print(f"MCP URL: {MCP_URL}")print("=" * 70)auth = OAuth(mcp_url=MCP_URL, client_name="ATS App", callback_port=CALLBACK_PORT)async with Client(MCP_URL, auth=auth) as client:# Step 1: Whoamiprint("\n--- 1. Checking Currently Signed-In Identity ---")try:who = await client.call_tool("whoami")who_data = who.data if hasattr(who, "data") else whoprint("Signed in identity returned by Microsoft:")print(json.dumps(who_data, indent=2, default=str))except Exception as e:print(f"whoami failed: {e}")# Step 2: Test search_filesprint("\n--- 2. Testing 'search_files' across multiple queries ---")search_queries = ["Canada", "Repository", "Calling Log", "Developer", "Engineer", "pdf", "docx"]accessible_items = []for q in search_queries:try:s_res = await client.call_tool("search_files", {"query": q, "max_results": 5})s_data = s_res.data if hasattr(s_res, "data") else s_resitems = s_data.get("items", []) if isinstance(s_data, dict) else (s_data if isinstance(s_data, list) else [])print(f" Search query '{q}': found {len(items)} items")for it in items:item_path = it.get("path") or it.get("name")print(f" * [{it.get('type')}] {item_path}")if item_path and item_path not in accessible_items:accessible_items.append(item_path)except Exception as e:print(f" Search query '{q}' error: {e}")# Step 3: If any accessible items were found, test get_file_info or read_fileif accessible_items:print(f"\n--- 3. Testing 'get_file_info' on accessible item: '{accessible_items[0]}' ---")try:info = await client.call_tool("get_file_info", {"path": accessible_items[0]})info_data = info.data if hasattr(info, "data") else infoprint(json.dumps(info_data, indent=2, default=str))except Exception as e:print(f"get_file_info error: {e}")else:print("\n[Summary] No items were returned by search_files. The signed-in account cannot query items in this library.")print("\n" + "=" * 70)if __name__ == "__main__":asyncio.run(main())
65 unmodified lines66676869707172737475767778798081828384858665 unmodified linesdef test_sharepoint_import_endpoint(client):payload = {"paths": ["Repository/AI Engineer/Arjun_Mehta_Lead_AI_Engineer.txt"]}response = client.post("/api/sharepoint/import", json=payload)assert response.status_code == 200data = response.json()assert data["total"] == 1assert data["successful"] == 1assert data["failed"] == 0item = data["items"][0]assert item["success"] is Trueassert item["filename"] == "Arjun_Mehta_Lead_AI_Engineer.txt"assert item.get("resumeText") is not Noneassert "PyTorch" in item.get("resumeText")def test_sharepoint_fetch_resumes_endpoint(client):payload = {65 unmodified lines666768697071727374757677787980818283848586878889909192939465 unmodified linesdef test_sharepoint_import_endpoint(client):payload = {"paths": ["Repository/AI Engineer/Arjun_Mehta_Lead_AI_Engineer.txt","Repository/.Net Developer/David_Miller_Senior_DotNet_Developer.docx","Repository/Adobe DevOps Specialist/Aarav_Sharma_Adobe_DevOps_Specialist.pdf",]}response = client.post("/api/sharepoint/import", json=payload)assert response.status_code == 200data = response.json()assert data["total"] == 3assert data["successful"] == 3assert data["failed"] == 0txt_item = next(it for it in data["items"] if it["filename"].endswith(".txt"))assert txt_item["success"] is Trueassert "PyTorch" in txt_item.get("resumeText")docx_item = next(it for it in data["items"] if it["filename"].endswith(".docx"))assert docx_item["success"] is Trueassert "C#" in docx_item.get("resumeText") or "Developer" in docx_item.get("resumeText")pdf_item = next(it for it in data["items"] if it["filename"].endswith(".pdf"))assert pdf_item["success"] is Trueassert "DevOps" in pdf_item.get("resumeText") or "AEM" in pdf_item.get("resumeText")def test_sharepoint_fetch_resumes_endpoint(client):payload = {
app/server.py+14
app/services/resume_parser.py+10
app/utils/file_validator.py+15-1
test_specific_folders.py+38-69
tests/test_sharepoint_mcp.py+16-8