-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender_google_docs.py
More file actions
97 lines (74 loc) · 2.92 KB
/
Copy pathrender_google_docs.py
File metadata and controls
97 lines (74 loc) · 2.92 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import sys
from urllib.parse import urlparse
import requests
import pandas as pd
from io import StringIO
def save(df: pd.DataFrame, path: str = "table.csv"):
df.to_csv(path, index=False)
return path
def download(url: str, table: int = 0):
parts = urlparse(url).path.split("/")
if len(parts) >= 5 and parts[1] == "document" and parts[2] == "d" and parts[3] == "e":
doc_id = parts[4]
export_url = f"https://docs.google.com/document/d/e/{doc_id}/pub"
elif len(parts) >= 4 and parts[1] == "document" and parts[2] == "d":
doc_id = parts[3]
export_url = f"https://docs.google.com/document/d/{doc_id}/export?format=html"
elif len(parts) >= 4 and parts[1] == "spreadsheets" and parts[2] == "d":
doc_id = parts[3]
export_url = f"https://docs.google.com/spreadsheets/d/{doc_id}/gviz/tq?tqx=out:html&gid=0"
else:
raise ValueError("URL does not contain the expected 'document'/'spreadsheets' segments.")
response = requests.get(export_url, timeout=30)
response.raise_for_status()
tables = pd.read_html(StringIO(response.text), header=0)
if table >= len(tables):
raise IndexError(
f"The document contains only {len(tables)} table(s)."
)
return tables[table]
def load(file: str = "table.csv"):
try:
return pd.read_csv(file)
except FileNotFoundError:
raise FileNotFoundError(f"'{file}' not found.")
def render(df: pd.DataFrame):
data = df.copy()
if str(data.iloc[0, 0]).strip().lower() == "x-coordinate":
data.columns = data.iloc[0].astype(str).str.strip()
data = data.iloc[1:].reset_index(drop=True)
data = data.rename(columns={
coluna: coluna.strip().lower().replace("-", "_")
for coluna in data.columns
})
positions_x = data["x_coordinate"].astype(int).to_numpy()
positions_y = data["y_coordinate"].astype(int).to_numpy()
characters = data["character"].astype(str).to_numpy()
largura = positions_x.max() + 1
altura = positions_y.max() + 1
grade = []
for _ in range(altura):
grade.append([" "] * largura)
for caractere, position_x, position_y in zip(characters, positions_x, positions_y):
grade[position_y][position_x] = caractere
rows = []
for row in grade:
rows.append("".join(row))
return "\n".join(rows)
def save_rendered_text(text: str, path: str = "rendered.txt") -> None:
with open(path, "w", encoding="utf-8") as f:
f.write(text)
def main():
if len(sys.argv) > 1:
url = " ".join(sys.argv[1:])
else:
print("This program downloads a table from a Google Docs document and renders it as text.")
url = input("Enter the Google Docs URL: ")
if not url:
raise SystemExit("No URL provided.")
save(download(url))
rendered = render(load("table.csv"))
print(rendered)
save_rendered_text(rendered)
if __name__ == "__main__":
main()