Here's the updated solution that handles hosted Microsoft Word documents (OneDrive, SharePoint, Office 365) along with Google Docs and traditional file URLs:
import requests
import os
import re
from urllib.parse import urlparse, parse_qs
class UnsupportedFileTypeError(Exception):
"""Custom exception for unsupported file types"""
pass
def infer_file_type(url):
"""
Infer file type from a URL. Supports PDF, Excel, Word documents including
Google Docs and Microsoft hosted documents.
Raises UnsupportedFileTypeError for other file types.
"""
# Check for Google Docs/Sheets first
google_type = detect_google_docs_type(url)
if google_type:
return google_type
# Check for Microsoft hosted documents
microsoft_type = detect_microsoft_hosted_type(url)
if microsoft_type:
return microsoft_type
# Check for other cloud services
cloud_type = detect_cloud_service_type(url)
if cloud_type:
return cloud_type
# Fall back to traditional file detection
return detect_traditional_file_type(url)
def detect_google_docs_type(url):
"""Detect Google Docs, Sheets, or Slides"""
google_patterns = {
'word': [
r'docs\.google\.com/document',
r'drive\.google\.com.*docx?',
],
'excel': [
r'docs\.google\.com/spreadsheets',
r'drive\.google\.com.*xlsx?',
],
'pdf': [
r'drive\.google\.com.*\.pdf',
]
}
for file_type, patterns in google_patterns.items():
for pattern in patterns:
if re.search(pattern, url, re.IGNORECASE):
return file_type
# Check if it's a Google Drive file by ID
if 'drive.google.com' in url or 'docs.google.com' in url:
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.head(url, headers=headers, allow_redirects=True, timeout=10)
final_url = response.url
if 'document' in final_url:
return 'word'
elif 'spreadsheets' in final_url:
return 'excel'
elif 'presentation' in final_url:
raise UnsupportedFileTypeError("Google Slides (presentation) files are not supported")
except requests.RequestException:
pass
return None
def detect_microsoft_hosted_type(url):
"""Detect Microsoft hosted documents (OneDrive, SharePoint, Office 365)"""
# Microsoft Office Online patterns
microsoft_patterns = {
'word': [
# OneDrive patterns
r'onedrive\.live\.com.*\.docx?',
r'1drv\.ms', # OneDrive short links
# SharePoint patterns
r'sharepoint\.com.*\.docx?',
r'[^/]+\.sharepoint\.com.*\.docx?',
# Office 365 patterns
r'[^/]+\.officeapps\.live\.com.*WOPISrc.*\.docx?',
r'office\.com.*\.docx?',
# Word Online patterns
r'word-edit\.officeapps\.live\.com',
r'word-view\.officeapps\.live\.com',
# Teams/SharePoint embedded docs
r'teams\.microsoft\.com.*\.docx?',
],
'excel': [
# OneDrive patterns
r'onedrive\.live\.com.*\.xlsx?',
# SharePoint patterns
r'sharepoint\.com.*\.xlsx?',
r'[^/]+\.sharepoint\.com.*\.xlsx?',
# Office 365 patterns
r'[^/]+\.officeapps\.live\.com.*WOPISrc.*\.xlsx?',
r'office\.com.*\.xlsx?',
# Excel Online patterns
r'excel-edit\.officeapps\.live\.com',
r'excel-view\.officeapps\.live\.com',
# Teams/SharePoint embedded sheets
r'teams\.microsoft\.com.*\.xlsx?',
],
'pdf': [
r'onedrive\.live\.com.*\.pdf',
r'sharepoint\.com.*\.pdf',
r'[^/]+\.sharepoint\.com.*\.pdf',
]
}
for file_type, patterns in microsoft_patterns.items():
for pattern in patterns:
if re.search(pattern, url, re.IGNORECASE):
return file_type
# Check for Microsoft Office Online URLs with parameters
if any(domain in url.lower() for domain in [
'officeapps.live.com', 'office.com', 'sharepoint.com',
'onedrive.live.com', '1drv.ms', 'teams.microsoft.com'
]):
try:
# Parse URL to check for file type indicators
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
# Check for WOPISrc parameter (Web Application Open Platform Interface)
if 'WOPISrc' in query_params:
wopi_src = query_params['WOPISrc'][0]
if '.docx' in wopi_src or '.doc' in wopi_src:
return 'word'
elif '.xlsx' in wopi_src or '.xls' in wopi_src:
return 'excel'
elif '.pdf' in wopi_src:
return 'pdf'
# Check for sourcedoc parameter
if 'sourcedoc' in query_params:
source_doc = query_params['sourcedoc'][0]
if '.docx' in source_doc or '.doc' in source_doc:
return 'word'
elif '.xlsx' in source_doc or '.xls' in source_doc:
return 'excel'
elif '.pdf' in source_doc:
return 'pdf'
# Check URL path for file extensions
path = parsed_url.path.lower()
if '.docx' in path or '.doc' in path:
return 'word'
elif '.xlsx' in path or '.xls' in path:
return 'excel'
elif '.pdf' in path:
return 'pdf'
# Try to make a request and check response
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.head(url, headers=headers, allow_redirects=True, timeout=10)
# Check final URL and content type
final_url = response.url.lower()
content_type = response.headers.get('content-type', '').lower()
if 'word' in final_url or 'document' in content_type:
return 'word'
elif 'excel' in final_url or 'spreadsheet' in content_type:
return 'excel'
elif 'pdf' in final_url or 'pdf' in content_type:
return 'pdf'
except requests.RequestException:
pass
return None
def detect_cloud_service_type(url):
"""Detect other cloud service file types"""
cloud_patterns = {
'word': [
r'dropbox\.com.*\.docx?',
r'box\.com.*\.docx?',
r'icloud\.com.*\.docx?',
],
'excel': [
r'dropbox\.com.*\.xlsx?',
r'box\.com.*\.xlsx?',
r'icloud\.com.*\.xlsx?',
],
'pdf': [
r'dropbox\.com.*\.pdf',
r'box\.com.*\.pdf',
r'icloud\.com.*\.pdf',
]
}
for file_type, patterns in cloud_patterns.items():
for pattern in patterns:
if re.search(pattern, url, re.IGNORECASE):
return file_type
return None
def detect_traditional_file_type(url):
"""Traditional file type detection for direct file URLs"""
SUPPORTED_TYPES = {
'pdf': {
'extensions': ['.pdf'],
'mime_types': ['application/pdf'],
'magic_bytes': [b'%PDF']
},
'excel': {
'extensions': ['.xls', '.xlsx', '.xlsm', '.xlsb'],
'mime_types': [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel.sheet.macroEnabled.12',
'application/vnd.ms-excel.sheet.binary.macroEnabled.12'
]
},
'word': {
'extensions': ['.doc', '.docx', '.docm'],
'mime_types': [
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-word.document.macroEnabled.12'
]
}
}
try:
# Check URL extension
parsed_url = urlparse(url)
filename = os.path.basename(parsed_url.path)
file_extension = os.path.splitext(filename)[1].lower()
file_type_from_ext = None
for file_type, info in SUPPORTED_TYPES.items():
if file_extension in info['extensions']:
file_type_from_ext = file_type
break
# Check content-type header
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
try:
response = requests.head(url, headers=headers, allow_redirects=True, timeout=10)
if response.status_code != 200:
response = requests.get(url, headers=headers, stream=True, timeout=10)
response.raise_for_status()
content_type = response.headers.get('content-type', '').lower()
file_type_from_mime = None
for file_type, info in SUPPORTED_TYPES.items():
if any(mime in content_type for mime in info['mime_types']):
file_type_from_mime = file_type
break
detected_type = file_type_from_ext or file_type_from_mime
except requests.RequestException:
detected_type = file_type_from_ext
if detected_type:
return detected_type
raise UnsupportedFileTypeError(
f"Unsupported file type. URL: {url}, "
f"Extension: {file_extension or 'None'}"
)
except Exception as e:
if isinstance(e, UnsupportedFileTypeError):
raise
else:
raise Exception(f"Error processing file: {str(e)}")
def get_downloadable_url(url, file_type):
"""Convert cloud service URLs to downloadable format if possible"""
# Google Docs export URLs
if 'docs.google.com/document' in url:
doc_id_match = re.search(r'/document/d/([a-zA-Z0-9-_]+)', url)
if doc_id_match:
doc_id = doc_id_match.group(1)
if file_type == 'word':
return f"https://docs.google.com/document/d/{doc_id}/export?format=docx"
elif file_type == 'pdf':
return f"https://docs.google.com/document/d/{doc_id}/export?format=pdf"
elif 'docs.google.com/spreadsheets' in url:
sheet_id_match = re.search(r'/spreadsheets/d/([a-zA-Z0-9-_]+)', url)
if sheet_id_match:
sheet_id = sheet_id_match.group(1)
if file_type == 'excel':
return f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
elif file_type == 'pdf':
return f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=pdf"
# Microsoft OneDrive direct download
elif 'onedrive.live.com' in url and '?download=1' not in url:
return url + ('&' if '?' in url else '?') + 'download=1'
# SharePoint direct download
elif 'sharepoint.com' in url and 'download=1' not in url:
return url + ('&' if '?' in url else '?') + 'download=1'
return url
# Example usage
if __name__ == "__main__":
test_urls = [
# Google Docs
"https://docs.google.com/document/d/1li3J7ZJx2spu-Ua0qXmhkTaMV5Pe6R5D6UOjvlwlWXs",
"https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
# Microsoft hosted (examples - replace with real URLs)
"https://onedrive.live.com/edit.aspx?resid=123&cid=456&app=Word",
"https://company.sharepoint.com/sites/team/Shared%20Documents/document.docx",
"https://word-edit.officeapps.live.com/we/wordeditorframe.aspx?WOPISrc=https://example.com/document.docx",
# Traditional files
"https://example.com/document.pdf",
"https://example.com/spreadsheet.xlsx",
# Unsupported
"https://example.com/image.jpg",
]
for url in test_urls:
try:
file_type = infer_file_type(url)
print(f"URL: {url}")
print(f"Detected file type: {file_type}")
downloadable_url = get_downloadable_url(url, file_type)
if downloadable_url != url:
print(f"Downloadable URL: {downloadable_url}")
print("-" * 80)
except UnsupportedFileTypeError as e:
print(f"Error: {e}")
print("-" * 80)
except Exception as e:
print(f"Unexpected error: {e}")
print("-" * 80)