import requests import sys # Configuration API_BASE_URL = "https://kalhdrawi-pdf1.hf.space" # API_BASE_URL = "http://localhost:7860" # Use this for local testing def convert_and_download(file_path): """Method 1: Convert and immediately download the binary file.""" url = f"{API_BASE_URL}/api/convert" print(f"\n--- Method 1: Direct Download ---\nUploading {file_path} to {url}...") try: with open(file_path, 'rb') as f: files = {'file': f} response = requests.post(url, files=files, stream=True) if response.status_code == 200: # Extract filename from header or default output_filename = "downloaded_output.pdf" if "content-disposition" in response.headers: print(f"Header: {response.headers['content-disposition']}") with open(output_filename, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) print(f"✅ Success! File saved to: {output_filename}") else: print(f"❌ Error {response.status_code}: {response.text}") except Exception as e: print(f"❌ Failed: {e}") def convert_and_get_link(file_path): """Method 2: Convert and get a URL to view/share.""" url = f"{API_BASE_URL}/api/convert/url" print(f"\n--- Method 2: Get View/Download Link ---\nUploading {file_path} to {url}...") try: with open(file_path, 'rb') as f: files = {'file': f} response = requests.post(url, files=files) if response.status_code == 200: data = response.json() print("✅ Success!") print(f"📄 Filename: {data['filename']}") print(f"🔗 Direct Link: {data['url']}") print("You can open this link in any browser.") else: print(f"❌ Error {response.status_code}: {response.text}") except Exception as e: print(f"❌ Failed: {e}") if __name__ == "__main__": # Create a dummy file if none exists to test target_file = "test_doc.docx" import os if not os.path.exists(target_file): with open(target_file, "w") as f: # Only works for txt content really, but simulates file presence f.write("This is a test file.") print(f"Created dummy {target_file} (Note: Real conversion needs a real DOCX)") if len(sys.argv) > 1: target_file = sys.argv[1] convert_and_download(target_file) convert_and_get_link(target_file)