File size: 925 Bytes
7be9035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import re

def convert_drive_url_to_direct(url: str) -> str:
    """
    Converts a Google Drive 'view' or 'open?id=' URL
    into a direct image/download URL usable in apps.
    """
    # Try to extract the file ID from either form
    patterns = [
        r'd/([a-zA-Z0-9_-]+)',        # e.g. .../file/d/<ID>/view
        r'id=([a-zA-Z0-9_-]+)'        # e.g. ...open?id=<ID>
    ]
    
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            file_id = match.group(1)
            return f"https://drive.google.com/uc?export=view&id={file_id}"
    
    raise ValueError("Invalid Google Drive URL format")

# Example usage
if __name__ == "__main__":
    url = "https://drive.google.com/file/d/1HTDB5VdQ1azGvkdeAuKK6MC09Pklh9Og/view?usp=drive_link"
    print(convert_drive_url_to_direct(url))
    # Output: https://drive.google.com/uc?export=view&id=1HTDB5VdQ1azGvkdeAuKK6MC09Pklh9Og