abdullah-1111 commited on
Commit
b278f6d
·
verified ·
1 Parent(s): b8b0baa

Update json-CR6.py

Browse files
Files changed (1) hide show
  1. json-CR6.py +140 -138
json-CR6.py CHANGED
@@ -1,138 +1,140 @@
1
- import base64
2
- import json
3
- import re
4
- import requests
5
- import os
6
-
7
- # مفتاح Gemini API
8
- API_KEY = "AIzaSyBr2-dUqHDZkk20hlWeEcpWnVVdkq9fqyE"
9
-
10
- # المجلد الذي يحتوي صور cr1
11
- cr1_images_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR6"
12
-
13
- # مجلد إخراج ملفات JSON
14
- output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR6\cr6_json"
15
-
16
- # Ensure output folder exists
17
- os.makedirs(output_json_folder, exist_ok=True)
18
-
19
- # Exact same prompt
20
- prompt = """
21
- يرجى استخراج الحقول التالية من مستند السجل التجاري (CR6) بالصورة، باللغة العربية فقط:
22
-
23
- - الكيان التجاري
24
- - حالة السجل
25
- - مدة المنشأة
26
- - الرقم الوطني الموحد للمنشأة
27
- - رابط المتجر الإكتروني
28
- - رأس المال
29
- - المدينة
30
- - صندوق البريد
31
- - الرمز البريدي
32
- - هاتف
33
- - تاريخ اصدار السجل
34
- - تاريخ انتهاء السجل
35
- - الموقع الاكتروني
36
- - العنوان
37
- - النشاط التجاري
38
-
39
- أرجو إعادة النتيجة بصيغة JSON بهذه المفاتيح فقط، وإذا أي حقل غير موجود فضع قيمته null:
40
-
41
- {
42
- "الكيان التجاري": null,
43
- "حالة السجل": null,
44
- "مدة المنشأة": null,
45
- "الرقم الوطني الموحد للمنشأة": null,
46
- "رابط المتجر الإكتروني": null,
47
- "رأس المال": null,
48
- "المدينة": null,
49
- "صندوق البريد": null,
50
- "الرمز البريدي": null,
51
- "هاتف": null,
52
- "تاريخ اصدار السجل": null,
53
- "تاريخ انتهاء السجل": null,
54
- "الموقع الاكتروني": null,
55
- "العنوان": null,
56
- "النشاط التجاري": null,
57
- "رقم المبنى": null,
58
- "الرقم الإضافي": null,
59
- "رقم الوحدة": null
60
- }
61
- """
62
-
63
- url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
64
- headers = {"Content-Type": "application/json"}
65
-
66
- # Iterate over all images
67
- for image_name in os.listdir(cr1_images_folder):
68
- if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
69
- continue
70
-
71
- image_path = os.path.join(cr1_images_folder, image_name)
72
- base_name = os.path.splitext(image_name)[0]
73
- output_file = os.path.join(output_json_folder, base_name + ".json")
74
-
75
- # Skip if JSON already exists
76
- if os.path.exists(output_file):
77
- print(f"⏩ Skipped {image_name} (JSON file already exists)")
78
- continue
79
-
80
- # Read image and convert to base64
81
- with open(image_path, "rb") as f:
82
- image_b64 = base64.b64encode(f.read()).decode()
83
-
84
- # Send request to Gemini API
85
- data = {
86
- "contents": [
87
- {
88
- "role": "user",
89
- "parts": [
90
- {"text": prompt},
91
- {
92
- "inline_data": {
93
- "mime_type": "image/jpeg",
94
- "data": image_b64
95
- }
96
- }
97
- ]
98
- }
99
- ]
100
- }
101
-
102
- try:
103
- response = requests.post(url, headers=headers, json=data)
104
- response.raise_for_status()
105
- response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
106
-
107
- match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
108
- if match:
109
- json_text = match.group(1)
110
- result = json.loads(json_text)
111
-
112
- # تقسيم حقل العنوان إذا كان موجود
113
- address = result.get("العنوان")
114
- if address:
115
- parts = address.strip().split()
116
- if len(parts) == 5:
117
- result["رقم المبنى"] = parts[0]
118
- result["المدينة"] = parts[1]
119
- result["الرمز البريدي"] = parts[2]
120
- result["الرقم الإضافي"] = parts[3]
121
- result["رقم الوحدة"] = parts[4]
122
- else:
123
- result["رقم المبنى"] = None
124
- result["المدينة"] = None
125
- result["الرمز البريدي"] = None
126
- result["الرقم الإضافي"] = None
127
- result["رقم الوحدة"] = None
128
-
129
- with open(output_file, "w", encoding="utf-8") as f:
130
- json.dump(result, f, ensure_ascii=False, indent=2)
131
-
132
- print(f"✅ Processed: {image_name}")
133
- else:
134
- print(f" Failed to extract JSON from: {image_name}")
135
- print(response_text)
136
-
137
- except Exception as e:
138
- print(f"❌ Error processing image {image_name}: {e}")
 
 
 
1
+ import base64
2
+ import json
3
+ import re
4
+ import requests
5
+ import os
6
+
7
+ # مفتاح Gemini API
8
+ API_KEY = "AIzaSyBr2-dUqHDZkk20hlWeEcpWnVVdkq9fqyE"
9
+
10
+ # المجلد الذي يحتوي صور cr1
11
+ cr1_images_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR6"
12
+
13
+ # مجلد إخراج ملفات JSON
14
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR6\cr6_json"
15
+
16
+ # Ensure output folder exists
17
+ os.makedirs(output_json_folder, exist_ok=True)
18
+
19
+ # Exact same prompt
20
+ # Exact same prompt
21
+ prompt = """
22
+ Please extract the following fields from the CR6 commercial registration document image, all in Arabic only:
23
+
24
+ - الكيان التجاري
25
+ - حالة السجل
26
+ - مدة المنشأة
27
+ - الرقم الوطني الموحد للمنشأة
28
+ - رابط المتجر الإكتروني
29
+ - رأس المال
30
+ - المدينة
31
+ - صندوق البريد
32
+ - الرمز البريدي
33
+ - هاتف
34
+ - تاريخ اصدار السجل
35
+ - تاريخ انتهاء السجل
36
+ - الموقع الاكتروني
37
+ - العنوان
38
+ - النشاط التجاري
39
+
40
+ Please return the result as JSON with the following exact keys, and if any field is missing, set its value to null:
41
+
42
+ {
43
+ "commercial_entity": null,
44
+ "registry_status": null,
45
+ "establishment_duration": null,
46
+ "unified_national_number": null,
47
+ "online_store_link": null,
48
+ "capital": null,
49
+ "city": null,
50
+ "po_box": null,
51
+ "postal_code": null,
52
+ "phone": null,
53
+ "registry_issue_date": null,
54
+ "registry_expiry_date": null,
55
+ "website": null,
56
+ "address": null,
57
+ "business_activity": null,
58
+ "building_number": null,
59
+ "additional_number": null,
60
+ "unit_number": null
61
+ }
62
+ """
63
+
64
+
65
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
66
+ headers = {"Content-Type": "application/json"}
67
+
68
+ # Iterate over all images
69
+ for image_name in os.listdir(cr1_images_folder):
70
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
71
+ continue
72
+
73
+ image_path = os.path.join(cr1_images_folder, image_name)
74
+ base_name = os.path.splitext(image_name)[0]
75
+ output_file = os.path.join(output_json_folder, base_name + ".json")
76
+
77
+ # Skip if JSON already exists
78
+ if os.path.exists(output_file):
79
+ print(f"⏩ Skipped {image_name} (JSON file already exists)")
80
+ continue
81
+
82
+ # Read image and convert to base64
83
+ with open(image_path, "rb") as f:
84
+ image_b64 = base64.b64encode(f.read()).decode()
85
+
86
+ # Send request to Gemini API
87
+ data = {
88
+ "contents": [
89
+ {
90
+ "role": "user",
91
+ "parts": [
92
+ {"text": prompt},
93
+ {
94
+ "inline_data": {
95
+ "mime_type": "image/jpeg",
96
+ "data": image_b64
97
+ }
98
+ }
99
+ ]
100
+ }
101
+ ]
102
+ }
103
+
104
+ try:
105
+ response = requests.post(url, headers=headers, json=data)
106
+ response.raise_for_status()
107
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
108
+
109
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
110
+ if match:
111
+ json_text = match.group(1)
112
+ result = json.loads(json_text)
113
+
114
+ # تقسيم حقل العنوان إذا كان موجود
115
+ address = result.get("العنوان")
116
+ if address:
117
+ parts = address.strip().split()
118
+ if len(parts) == 5:
119
+ result["رقم المبنى"] = parts[0]
120
+ result["المدينة"] = parts[1]
121
+ result["الرمز البريدي"] = parts[2]
122
+ result["الرقم الإضافي"] = parts[3]
123
+ result["رقم الوحدة"] = parts[4]
124
+ else:
125
+ result["رقم المبنى"] = None
126
+ result["المدينة"] = None
127
+ result["الرمز البريدي"] = None
128
+ result["الرقم الإضافي"] = None
129
+ result["رقم الوحدة"] = None
130
+
131
+ with open(output_file, "w", encoding="utf-8") as f:
132
+ json.dump(result, f, ensure_ascii=False, indent=2)
133
+
134
+ print(f" Processed: {image_name}")
135
+ else:
136
+ print(f"❌ Failed to extract JSON from: {image_name}")
137
+ print(response_text)
138
+
139
+ except Exception as e:
140
+ print(f"❌ Error processing image {image_name}: {e}")