File size: 7,182 Bytes
e7102e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""
Upload Odia OCR Benchmark Dataset to HuggingFace Hub

Converts local images + metadata.csv to HuggingFace Dataset format and pushes.
"""

import argparse
from pathlib import Path

from datasets import Dataset, Features, Value, Image
from huggingface_hub import HfApi
import pandas as pd


BENCHMARK_DIR = Path(__file__).parent.parent / "benchmark_dataset"
CSV_PATH = BENCHMARK_DIR / "final_hf.csv"


def resolve_image_path(raw_path: str) -> Path:
    """Resolve image paths from metadata across common path styles."""
    p = Path(str(raw_path).strip())

    # 1) Already absolute
    if p.is_absolute():
        return p

    # 2) Relative to project root: benchmark_dataset/images/...
    if p.parts and p.parts[0] == "benchmark_dataset":
        return (BENCHMARK_DIR.parent / p).resolve()

    # 3) Relative to benchmark dir: images/...
    return (BENCHMARK_DIR / p).resolve()


def load_local_dataset() -> Dataset:
    """Load local images and metadata into a HuggingFace Dataset."""
    print(f"Loading metadata from {CSV_PATH}...")
    
    if not CSV_PATH.exists():
        raise FileNotFoundError(f"Metadata CSV not found: {CSV_PATH}")
    
    df = pd.read_csv(CSV_PATH)
    print(f"Found {len(df)} samples in metadata")
    
    # Normalize image paths, supporting:
    # - images/...
    # - benchmark_dataset/images/...
    # - absolute paths
    df["image_path"] = df["image_path"].apply(lambda p: str(resolve_image_path(p)))
    
    # Verify images exist
    missing = []
    for idx, row in df.iterrows():
        if not Path(row["image_path"]).exists():
            missing.append(row["image_path"])
    
    if missing:
        print(f"Warning: {len(missing)} images not found:")
        for p in missing[:5]:
            print(f"  - {p}")
        if len(missing) > 5:
            print(f"  ... and {len(missing) - 5} more")
        
        # Filter out missing images
        df = df[df["image_path"].apply(lambda p: Path(p).exists())]
        print(f"Continuing with {len(df)} valid samples")
    
    if "id" not in df.columns:
        raise ValueError(
            f"Required column 'id' not found in {CSV_PATH}. "
            "Please add an 'id' column before upload."
        )

    # Create dataset with Image feature
    features = Features({
        "id": Value("int64"),
        "image": Image(),
        "ground_truth": Value("string"),
        "category": Value("string"),

    })
    
    # Rename image_path to image for HF Dataset
    data = {
        "id": df["id"].tolist(),
        "image": df["image_path"].tolist(),
        "ground_truth": df["ground_truth"].tolist(),
        "category": df["category"].tolist(),

    }
    
    dataset = Dataset.from_dict(data, features=features)
    print(f"Created HuggingFace Dataset with {len(dataset)} samples")
    
    return dataset


def push_to_hub(dataset: Dataset, repo_id: str, private: bool = False):
    """Push dataset to HuggingFace Hub."""
    print(f"\nPushing to HuggingFace Hub: {repo_id}")
    print(f"Private: {private}")
    
    dataset.push_to_hub(
        repo_id,
        private=private,
        commit_message="Upload Odia OCR benchmark dataset",
    )
    
    print(f"\nDataset uploaded to: https://huggingface.co/datasets/{repo_id}")


def push_dataset_card(repo_id: str, card_content: str):
    """Upload dataset card as README.md to HuggingFace Hub."""
    api = HfApi()
    api.upload_file(
        path_or_fileobj=card_content.encode("utf-8"),
        path_in_repo="README.md",
        repo_id=repo_id,
        repo_type="dataset",
        commit_message="Add dataset card README",
    )
    print(f"Dataset card uploaded: https://huggingface.co/datasets/{repo_id}/blob/main/README.md")


def create_dataset_card(repo_id: str):
    """Create a dataset card (README.md) for HuggingFace."""
    card_content = f"""---
license: cc-by-4.0
task_categories:
  - image-to-text
language:
  - or
tags:
  - ocr
  - odia
  - oriya
  - indic
  - benchmark
size_categories:
  - n<1K
---

# Odia OCR Benchmark Dataset

## Description

A curated benchmark dataset for evaluating OCR models on Odia (Oriya) text recognition.
Contains handwritten, printed, scene text, newspaper, books, and digital categories,
including both short samples and long-text examples for OCR evaluation.

## Dataset Structure

- **id**: Unique identifier for each sample
- **image**: The input image (PIL Image)
- **ground_truth**: The correct Odia text transcription
- **category**: Type of text (handwritten, printed, scene_text, newspaper, books, digital)



## Usage

```python
from datasets import load_dataset

dataset = load_dataset("{repo_id}")

# Access a sample
sample = dataset["train"][0]
sample_id = sample["id"]
image = sample["image"]
text = sample["ground_truth"]
```

## Categories

| Category      | Description                                           |
| ------------- | ----------------------------------------------------- |
| handwritten   | Handwritten Odia text (word/short phrase level)       |
| printed       | Printed/typed Odia text                               |
| scene_text    | Text in natural scenes (signboards, posters, etc.)    |
| newspaper     | Odia newspaper clippings (including long text)        |
| books         | Scanned Odia book pages (including long text)         |
| digital       | Screenshots from Odia digital content                 |

## Sources

- `OdiaGenAIOCR/odia-ocr-merged` (handwritten)
- `darknight054/indic-mozhi-ocr` with config `oriya` (printed)
- `darknight054/indicstr12-crops` with config `odia` (scene_text)
- `newspaper`: Odia newspaper scans/clippings
- `books`: Odia book page images
- `digital`: odia digital content

## Notes

- Includes long-text samples for paragraph-level OCR evaluation.
- The `source` field records origin for each sample.

## License

CC-BY-4.0
"""
    return card_content


def main():
    parser = argparse.ArgumentParser(
        description="Upload Odia OCR benchmark dataset to HuggingFace Hub"
    )
    parser.add_argument(
        "--repo",
        type=str,
        required=True,
        help="HuggingFace repo ID (e.g., 'username/odia-ocr-benchmark')",
    )
    parser.add_argument(
        "--private",
        action="store_true",
        help="Make the dataset private",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Load and validate dataset without uploading",
    )
    
    args = parser.parse_args()
    
    print("=" * 60)
    print("Upload Odia OCR Benchmark to HuggingFace")
    print("=" * 60)
    
    # Load local dataset
    dataset = load_local_dataset()
    
    # Show sample
    print("\nSample from dataset:")
    sample = dataset[0]
    print(f"  id: {sample['id']}")
    print(f"  ground_truth: {sample['ground_truth']}")
    print(f"  category: {sample['category']}")

    
    if args.dry_run:
        print("\n[DRY RUN] Dataset validated. Not uploading.")
        return
    
    # Push to hub
    push_to_hub(dataset, args.repo, private=args.private)

    # Push dataset card
    card_content = create_dataset_card(args.repo)
    push_dataset_card(args.repo, card_content)


if __name__ == "__main__":
    main()