Felix92 commited on
Commit
a9f7f11
·
1 Parent(s): a5cac06
Files changed (2) hide show
  1. app.py +149 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import logging
4
+ import json
5
+ import hashlib
6
+ from pathlib import Path
7
+ from fontTools.ttLib import TTFont, TTLibError
8
+ from huggingface_hub import HfApi
9
+
10
+ logging.basicConfig(level=logging.INFO)
11
+
12
+ API = HfApi()
13
+ TOKEN = os.environ.get("TOKEN", "your_token_here") # fallback for debugging
14
+ REPO_ID = "Felix92/docTR-resource-collection"
15
+
16
+ def get_supported_chars(font_path: Path) -> list[str]:
17
+ try:
18
+ font = TTFont(font_path)
19
+ supported_chars = set()
20
+ for table in font["cmap"].tables:
21
+ supported_chars.update(table.cmap.keys())
22
+ chars = [chr(code_point) for code_point in sorted(supported_chars)]
23
+ return [char for char in chars if char.isprintable()]
24
+ except TTLibError as e:
25
+ logging.error(f"Error reading font file {font_path}: {e}")
26
+ return []
27
+ except Exception as e:
28
+ logging.error(f"Unexpected error reading font file {font_path}: {e}")
29
+ return []
30
+
31
+ def get_sha256(file_path: Path) -> str:
32
+ hash_sha256 = hashlib.sha256()
33
+ with open(file_path, "rb") as f:
34
+ for chunk in iter(lambda: f.read(8192), b""):
35
+ hash_sha256.update(chunk)
36
+ return hash_sha256.hexdigest()
37
+
38
+ def file_exists_on_hub(file_name: str, subfolder: str) -> bool:
39
+ files = API.list_repo_files(
40
+ repo_id=REPO_ID,
41
+ repo_type="dataset",
42
+ token=TOKEN,
43
+ )
44
+ return any(file.startswith(f"{subfolder}/{file_name}") for file in files)
45
+
46
+ def _upload_hub(file_path: str, subfolder: str, sha_hash: str) -> None:
47
+ filename = f"{sha_hash}_{Path(file_path).name}"
48
+ repo_path = f"{subfolder}/{filename}"
49
+ API.upload_file(
50
+ path_or_fileobj=file_path,
51
+ path_in_repo=repo_path,
52
+ token=TOKEN,
53
+ repo_type="dataset",
54
+ repo_id=REPO_ID,
55
+ )
56
+ logging.info(f"Uploaded {repo_path}")
57
+
58
+ def handle_uploads(font_upload, wordlist_upload, agree):
59
+ if not agree:
60
+ return gr.Markdown("You must agree to the terms and conditions before proceeding."), None, None, None
61
+
62
+ try:
63
+ if font_upload:
64
+ font_path = Path(font_upload)
65
+ font_sha = get_sha256(font_path)
66
+ if file_exists_on_hub(font_sha, "fonts"):
67
+ return gr.update(visible=False), gr.Markdown("<div style='text-align: center;'><h3>This font was already uploaded.</h3></div>"), gr.update(value=None), gr.update(value=None)
68
+
69
+ supported_chars = get_supported_chars(font_path)
70
+ if not supported_chars:
71
+ return gr.update(visible=False), gr.Markdown("<div style='text-align: center;'><h3>No supported characters found in the font file.</h3></div>"), gr.update(value=None), gr.update(value=None)
72
+ metadata = {
73
+ "font_name": font_path.stem,
74
+ "supported_characters": supported_chars,
75
+ }
76
+ json_path = font_path.with_suffix(".json")
77
+ with open(json_path, "w", encoding="utf-8") as f:
78
+ json.dump(metadata, f, ensure_ascii=False, indent=2)
79
+
80
+ json_sha = get_sha256(json_path)
81
+
82
+ _upload_hub(str(font_path), "fonts", font_sha)
83
+ _upload_hub(str(json_path), "fonts", json_sha)
84
+
85
+ if wordlist_upload:
86
+ wordlist_path = Path(wordlist_upload)
87
+ wordlist_sha = get_sha256(wordlist_path)
88
+ if file_exists_on_hub(wordlist_sha, "wordlists"):
89
+ return gr.update(visible=False), gr.Markdown("<div style='text-align: center;'><h3>This wordlist was already uploaded.</h3></div>"), gr.update(value=None), gr.update(value=None)
90
+
91
+ _upload_hub(str(wordlist_path), "wordlists", wordlist_sha)
92
+
93
+ return gr.update(visible=False), gr.Markdown("<div style='text-align: center;'><h3>Upload was successful! You can upload another item.</h3></div>"), gr.update(value=None), gr.update(value=None)
94
+
95
+ except Exception as e:
96
+ logging.exception("Upload failed")
97
+ return gr.update(visible=False), gr.Markdown(f"<div style='text-align: center;'><h3>An error occurred: {e}</h3></div>"), gr.update(value=None), gr.update(value=None)
98
+
99
+ with gr.Blocks(fill_height=True) as demo:
100
+ agreement_markdown = gr.Markdown(
101
+ """
102
+ <div style="text-align: center;">
103
+ <h1>File Upload Agreement</h1>
104
+
105
+ <h3>This is a Hugging Face space for the docTR/OnnxTR community to collect wordlists and fonts for the following project/s:</h3>
106
+
107
+ <h3><a href="https://github.com/mindee/doctr">docTR</a></h3>
108
+
109
+ <h3><a href="https://github.com/felixdittrich92/OnnxTR">OnnxTR</a></h3>
110
+ </div>
111
+
112
+ <h3>The uploaded wordlists and fonts will be used to generate synthetic data.</h3>
113
+
114
+ <h3>All uploaded files can be found here: <a href="https://huggingface.co/datasets/Felix92/docTR-resource-collection">Hugging Face dataset</a></h3>
115
+
116
+ <br>
117
+ <br>
118
+
119
+ <h3>By uploading a wordlist or font, you explicitly agree to the following terms:</h3>
120
+
121
+ <h3>1. You affirm that you are the owner or have the necessary rights to upload and share the wordlist or font.</h3>
122
+
123
+ <h3>2. You agree that the uploaded wordlists / fonts will be made publicly available to everyone.</h3>
124
+
125
+ <h3>3. You agree that the uploaded wordlists / fonts can be used for any purpose, including commercial use, by any third party.</h3>
126
+ """
127
+ )
128
+ agree_button = gr.Button("I Agree to the Terms and Conditions")
129
+ agree_state = gr.State(value=False)
130
+
131
+ with gr.Column(visible=False) as upload_section:
132
+ success_message = gr.Markdown(visible=True)
133
+ font_upload = gr.File(label="Upload Font File [TTF | OTF]", file_types=[".ttf", ".otf"], type="filepath")
134
+ wordlist_upload = gr.File(label="Upload Wordlist [TXT]", file_types=[".txt"], type="filepath")
135
+ submit_button = gr.Button("Submit")
136
+
137
+ def toggle_agreement_visibility():
138
+ return gr.update(visible=False), gr.update(visible=False), True, gr.update(visible=True)
139
+
140
+ agree_button.click(fn=toggle_agreement_visibility, inputs=None, outputs=[agreement_markdown, agree_button, agree_state, upload_section])
141
+
142
+ submit_button.click(
143
+ fn=handle_uploads,
144
+ inputs=[font_upload, wordlist_upload, agree_state],
145
+ outputs=[agree_button, success_message, font_upload, wordlist_upload],
146
+ )
147
+
148
+ if __name__ == "__main__":
149
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=5.0.0, <6.0.0
2
+ fonttools>=4.57.0, <5.0.0
3
+ huggingface-hub>=0.25.2, <1.0.0