vineet124jig commited on
Commit
ad6bc96
·
verified ·
1 Parent(s): 64be04c

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +16 -5
  2. app.py +222 -0
  3. requirements.txt +3 -0
README.md CHANGED
@@ -1,13 +1,24 @@
1
  ---
2
- title: VOCR
3
- emoji: 🏃
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 5.34.2
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
 
 
 
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
  ---
2
+ title: vOCR
3
+ emoji: 🔥
4
+ colorFrom: indigo
5
+ colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.34.2
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ tags:
12
+ - OCR
13
+ - vision
14
+ - text-recognition
15
+ - image-to-text
16
+ - document-processing
17
+ - gradio
18
+ - api
19
+ - jigsawstack
20
+ short_description: Extract text from images with Vocr API
21
  ---
22
 
23
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
24
+ Explore the Vocr API: https://jigsawstack.com/docs/api-reference/ai/voc
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import os
5
+ import time
6
+ from collections import defaultdict
7
+
8
+ BASE_URL = "https://api.jigsawstack.com/v1"
9
+ headers = {
10
+ "x-api-key": os.getenv("JIGSAWSTACK_API_KEY")
11
+ }
12
+
13
+
14
+ # Rate limiting configuration
15
+ request_times = defaultdict(list)
16
+ MAX_REQUESTS = 1 # Maximum requests per time window
17
+ TIME_WINDOW = 3600 # Time window in seconds (1 hour)
18
+
19
+ def get_real_ip(request: gr.Request):
20
+ """Extract real IP address using x-forwarded-for header or fallback"""
21
+ if not request:
22
+ return "unknown"
23
+
24
+ forwarded = request.headers.get("x-forwarded-for")
25
+ if forwarded:
26
+ ip = forwarded.split(",")[0].strip() # First IP in the list is the client's
27
+ else:
28
+ ip = request.client.host # fallback
29
+ return ip
30
+
31
+ def check_rate_limit(request: gr.Request):
32
+ """Check if the current request exceeds rate limits"""
33
+ if not request:
34
+ return True, "Rate limit check failed - no request info"
35
+
36
+ ip = get_real_ip(request)
37
+ now = time.time()
38
+
39
+ # Clean up old timestamps outside the time window
40
+ request_times[ip] = [t for t in request_times[ip] if now - t < TIME_WINDOW]
41
+
42
+ print(f"Request times: {request_times[ip]}")
43
+
44
+ # Check if rate limit exceeded
45
+ if len(request_times[ip]) >= MAX_REQUESTS:
46
+ time_remaining = int(TIME_WINDOW - (now - request_times[ip][0]))
47
+ time_remaining_minutes = round(time_remaining / 60, 1)
48
+ time_window_minutes = round(TIME_WINDOW / 60, 1)
49
+
50
+ return False, f"Rate limit exceeded. You can make {MAX_REQUESTS} requests per {time_window_minutes} minutes. Try again in {time_remaining_minutes} minutes."
51
+
52
+ # Add current request timestamp
53
+ request_times[ip].append(now)
54
+ return True, ""
55
+
56
+
57
+ # ----------------- JigsawStack API Wrasppers ------------------
58
+
59
+ def vocr(source_type, image_url, file_store_key, prompt_str, page_range_str, request: gr.Request):
60
+ # Check rate limit first
61
+ rate_limit_ok, rate_limit_msg = check_rate_limit(request)
62
+ if not rate_limit_ok:
63
+ return (
64
+ rate_limit_msg, # status
65
+ None, # image
66
+ gr.update(visible=False), # context JSON
67
+ gr.update(visible=False), # tags
68
+ gr.update(visible=False), # has_text
69
+ gr.update(visible=False), # sections JSON
70
+ )
71
+
72
+ def error_response(message, img_src):
73
+ return (
74
+ message,
75
+ img_src,
76
+ gr.update(visible=False),
77
+ gr.update(visible=False),
78
+ gr.update(visible=False),
79
+ gr.update(visible=False)
80
+ )
81
+
82
+ image_to_display = image_url if source_type == "URL" else None
83
+
84
+ try:
85
+ payload = {}
86
+ # Validate prompts - ensure a prompt is always provided.
87
+ if not prompt_str or not prompt_str.strip():
88
+ return error_response("Error: Prompt is required.", image_to_display)
89
+
90
+ prompts = [p.strip() for p in prompt_str.split(',') if p.strip()]
91
+ if not prompts:
92
+ return error_response("Error: Prompt cannot be empty or just commas.", image_to_display)
93
+
94
+ # The API can handle an array of prompts, which is more robust
95
+ # and avoids potential issues with the response format.
96
+ payload["prompt"] = prompts
97
+
98
+ # Validate page range
99
+ if page_range_str and page_range_str.strip():
100
+ try:
101
+ parts = [int(p.strip()) for p in page_range_str.split(',')]
102
+ if len(parts) != 2:
103
+ raise ValueError("Page range must be two numbers (e.g., 1,10).")
104
+ start_page, end_page = parts
105
+ if not (start_page > 0 and end_page > 0):
106
+ raise ValueError("Page numbers must be positive.")
107
+ if start_page > end_page:
108
+ raise ValueError("Start page cannot be greater than end page.")
109
+ if (end_page - start_page) >= 10:
110
+ raise ValueError("Page range cannot span more than 10 pages.")
111
+ payload["page_range"] = [start_page, end_page]
112
+ except (ValueError, TypeError) as e:
113
+ return error_response(f"Error: Invalid page range format - {e}", image_to_display)
114
+
115
+ if source_type == "URL":
116
+ if not image_url or not image_url.strip():
117
+ return error_response("Error: Image URL is required.", image_to_display)
118
+ payload["url"] = image_url.strip()
119
+
120
+ elif source_type == "File Store Key":
121
+ if not file_store_key or not file_store_key.strip():
122
+ return error_response("Error: File Store Key is required.", image_to_display)
123
+ payload["file_store_key"] = file_store_key.strip()
124
+ else:
125
+ return error_response("Error: Invalid image source selected.", image_to_display)
126
+
127
+ response = requests.post(f"{BASE_URL}/vocr", headers=headers, json=payload)
128
+ response.raise_for_status()
129
+ result = response.json()
130
+
131
+ if not result.get("success"):
132
+ return error_response(f"Error: vOCR failed - {result.get('message', 'Unknown error')}", image_to_display)
133
+
134
+ context = result.get("context", {})
135
+ tags = ", ".join(result.get("tags", []))
136
+ has_text = str(result.get("has_text", "N/A"))
137
+ sections = result.get("sections", [])
138
+
139
+ status = "✅ Successfully processed image with vOCR."
140
+
141
+ return (
142
+ status,
143
+ image_to_display,
144
+ gr.update(value=context, visible=True if context else False),
145
+ gr.update(value=tags, visible=True if tags else False),
146
+ gr.update(value=has_text, visible=True),
147
+ gr.update(value=sections, visible=True if sections else False)
148
+ )
149
+
150
+ except requests.exceptions.RequestException as e:
151
+ return error_response(f"Request failed: {str(e)}", image_to_display)
152
+ except Exception as e:
153
+ return error_response(f"An unexpected error occurred: {str(e)}", image_to_display)
154
+
155
+ # ----------------- Gradio UI ------------------
156
+
157
+ with gr.Blocks() as demo:
158
+ gr.Markdown("""
159
+ <div style='text-align: center; margin-bottom: 24px;'>
160
+ <h1 style='font-size:2.2em; margin-bottom: 0.2em;'>🧩 vOCR</h1>
161
+ <p style='font-size:1.2em; margin-top: 0;'>Extract text from images with advanced AI models.</p>
162
+ <p style='font-size:1em; margin-top: 0.5em;'>For more details and API usage, see the <a href='https://jigsawstack.com/docs/api-reference/ai/vocr' target='_blank'>documentation</a>.</p>
163
+ </div>
164
+ """)
165
+
166
+ with gr.Row():
167
+ with gr.Column(scale=1):
168
+ gr.Markdown("#### Image Source")
169
+ vocr_source_type = gr.Radio(
170
+ choices=["URL", "File Store Key"],
171
+ label="Choose Image Source",
172
+ value="URL"
173
+ )
174
+ vocr_image_url = gr.Textbox(
175
+ label="Image URL",
176
+ placeholder="https://media.snopes.com/2021/08/239918331_10228097135359041_3825446756894757753_n.jpg",
177
+ visible=True
178
+ )
179
+ vocr_file_key = gr.Textbox(
180
+ label="File Store Key",
181
+ placeholder="your-file-store-key",
182
+ visible=False
183
+ )
184
+ vocr_prompts = gr.Textbox(
185
+ label="Prompts (comma-separated)",
186
+ placeholder="total_price, tax, store_name",
187
+ info="Prompts to guide data extraction from the image."
188
+ )
189
+ vocr_page_range = gr.Textbox(
190
+ label="Page Range (Optional)",
191
+ placeholder="e.g., 1,10",
192
+ info="For multi-page docs. Max 10 pages."
193
+ )
194
+ vocr_btn = gr.Button("Analyze Image", variant="primary")
195
+
196
+ with gr.Column(scale=2):
197
+ gr.Markdown("#### Analysis Results")
198
+ vocr_status = gr.Textbox(label="Status", interactive=False)
199
+ vocr_image_display = gr.Image(label="Analyzed Image")
200
+ vocr_context = gr.JSON(label="Extracted Context", visible=False)
201
+ vocr_tags = gr.Textbox(label="Detected Tags", interactive=False, visible=False)
202
+ vocr_has_text = gr.Textbox(label="Text Detected?", interactive=False, visible=False)
203
+ vocr_sections = gr.JSON(label="Full OCR Sections", visible=False)
204
+
205
+ def update_vocr_source(source_type):
206
+ is_url = source_type == "URL"
207
+ return gr.update(visible=is_url), gr.update(visible=not is_url)
208
+
209
+ vocr_source_type.change(
210
+ update_vocr_source,
211
+ inputs=vocr_source_type,
212
+ outputs=[vocr_image_url, vocr_file_key]
213
+ )
214
+
215
+ vocr_btn.click(
216
+ vocr,
217
+ inputs=[vocr_source_type, vocr_image_url, vocr_file_key, vocr_prompts, vocr_page_range],
218
+ outputs=[vocr_status, vocr_image_display, vocr_context, vocr_tags, vocr_has_text, vocr_sections]
219
+ )
220
+
221
+
222
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ requests
3
+ Pillow