abdullah-1111 commited on
Commit
7c5647d
·
verified ·
1 Parent(s): 81fdfcf

Update json-CR2.py

Browse files
Files changed (1) hide show
  1. json-CR2.py +166 -164
json-CR2.py CHANGED
@@ -1,164 +1,166 @@
1
- import base64
2
- import json
3
- import re
4
- import requests
5
- import os
6
- import time
7
-
8
- API_KEY = "AIzaSyBr2-dUqHDZkk20hlWeEcpWnVVdkq9fqyE"
9
-
10
- cr1_images_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR2"
11
- output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR2\cr2_json"
12
-
13
- os.makedirs(output_json_folder, exist_ok=True)
14
-
15
- prompt = """
16
- يرجى استخراج الحقول التالية من صورة مستند CR2 (السجل التجاري 2)، جميعها بالعربية فقط:
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
- أرجو إعادة النتيجة بصيغة JSON بهذه المفاتيح فقط، وإذا أي حقل غير موجود فضع قيمته null:
51
-
52
- {
53
- "الرقم": null,
54
- "التاريخ": null,
55
- "الرقم الموحد للمنشأة": null,
56
- "الاسم التجاري للمؤسسة": null,
57
- "مركزها الرئيسي": null,
58
- "هاتف": null,
59
- "الرمز البريدي": null,
60
- "اسم التاجر": null,
61
- "الجنسية": null,
62
- "تاريخ الميلاد": null,
63
- "رقم السجل المدني-الإقامة": null,
64
- "تاريخه": null,
65
- "مصدره": null,
66
- "رقم الحفيظة-الجواز": null,
67
- "تاريخه_2": null,
68
- "مصدرة": null,
69
- "النشاط": null,
70
- "رأس المال": null,
71
- "اسم المدير او الوكيل المفوض": null,
72
- "الجنسية_2": null,
73
- "تاريخ الميلاد_2": null,
74
- "رقم السجل المدني-الإقامة_2": null,
75
- "تاريخه_3": null,
76
- "مصدره_2": null,
77
- "سلطات المدير": null,
78
- "يشهد مكتب السجل التجاري بمدينة": null,
79
- "بأنه تم تسجيل المؤسسة المذكورة أعلاه بمدينة": null,
80
- "تنتهي صلاحية الشهادات في": null,
81
- "بموجب الإيصال رقم": null,
82
- "تاريخ_الإيصال": null,
83
- "مدير السجل التجاري": null
84
- }
85
- """
86
-
87
- url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
88
- headers = {"Content-Type": "application/json"}
89
-
90
- def split_address(address):
91
- parts = [p.strip() for p in address.split("،")]
92
- while len(parts) < 4:
93
- parts.append(None)
94
- return parts
95
-
96
- for image_name in os.listdir(cr1_images_folder):
97
- if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
98
- continue
99
-
100
- image_path = os.path.join(cr1_images_folder, image_name)
101
- base_name = os.path.splitext(image_name)[0]
102
- output_file = os.path.join(output_json_folder, base_name + ".json")
103
-
104
- if os.path.exists(output_file):
105
- print(f"Skipped {image_name} (JSON file already exists)")
106
- continue
107
-
108
- with open(image_path, "rb") as f:
109
- image_b64 = base64.b64encode(f.read()).decode()
110
-
111
- data = {
112
- "contents": [
113
- {
114
- "role": "user",
115
- "parts": [
116
- {"text": prompt},
117
- {
118
- "inline_data": {
119
- "mime_type": "image/jpeg",
120
- "data": image_b64
121
- }
122
- }
123
- ]
124
- }
125
- ]
126
- }
127
-
128
- try:
129
- response = requests.post(url, headers=headers, json=data)
130
- response.raise_for_status()
131
- response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
132
-
133
- # استخدام التعبير المنتظم الصحيح
134
- match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
135
- if match:
136
- json_text = match.group(1)
137
- result = json.loads(json_text)
138
-
139
- # تقسيم العنوان إلى أجزاء منفصلة
140
- if "مركزها الرئيسي" in result and result["مركزها الرئيسي"]:
141
- parts = split_address(result["مركزها الرئيسي"])
142
- result["رقم المبنى"] = parts[0]
143
- result["اسم الشارع"] = parts[1]
144
- result["اسم الحي"] = parts[2]
145
- result["الرقم الإضافي"] = parts[3]
146
- else:
147
- result["رقم المبنى"] = None
148
- result["اسم الشارع"] = None
149
- result["اسم الحي"] = None
150
- result["الرقم الإضافي"] = None
151
-
152
- with open(output_file, "w", encoding="utf-8") as f:
153
- json.dump(result, f, ensure_ascii=False, indent=2)
154
-
155
- print(f"✅ Processed: {image_name}")
156
-
157
- else:
158
- print(f"❌ Failed to extract JSON from: {image_name}")
159
- print(response_text)
160
-
161
- time.sleep(3) # ينتظر 3 ثواني قبل إرسال الصورة التالية
162
-
163
- except Exception as e:
164
- print(f"❌ Error processing image {image_name}: {e}")
 
 
 
1
+ import base64
2
+ import json
3
+ import re
4
+ import requests
5
+ import os
6
+ import time
7
+
8
+ API_KEY = "AIzaSyBr2-dUqHDZkk20hlWeEcpWnVVdkq9fqyE"
9
+
10
+ cr1_images_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR2"
11
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR2\cr2_json"
12
+
13
+ os.makedirs(output_json_folder, exist_ok=True)
14
+
15
+ prompt = """
16
+ Please extract the following fields from the CR2 (Commercial Registration 2) document image. Extract all text in Arabic, but return the output in JSON format using the exact English keys listed below. If any field is missing, set its value to null.
17
+
18
+ Fields to extract (from Arabic content):
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
+ Return the result in JSON format with the following keys:
53
+
54
+ {
55
+ "document_number": null,
56
+ "document_date": null,
57
+ "unified_establishment_number": null,
58
+ "institution_name": null,
59
+ "main_office_address": null,
60
+ "phone": null,
61
+ "postal_code": null,
62
+ "merchant_name": null,
63
+ "nationality": null,
64
+ "birth_date": null,
65
+ "national_id": null,
66
+ "national_id_issue_date": null,
67
+ "national_id_issue_place": null,
68
+ "passport_number": null,
69
+ "passport_issue_date": null,
70
+ "passport_issuer": null,
71
+ "business_activity": null,
72
+ "capital": null,
73
+ "manager_name": null,
74
+ "manager_nationality": null,
75
+ "manager_birth_date": null,
76
+ "manager_national_id": null,
77
+ "manager_id_issue_date": null,
78
+ "manager_id_issue_place": null,
79
+ "manager_authority": null,
80
+ "registry_office_city": null,
81
+ "registered_in_city": null,
82
+ "certificate_expiry_date": null,
83
+ "receipt_number": null,
84
+ "receipt_date": null,
85
+ "registry_officer": null
86
+ }
87
+ """
88
+
89
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
90
+ headers = {"Content-Type": "application/json"}
91
+
92
+ def split_address(address):
93
+ parts = [p.strip() for p in address.split("،")]
94
+ while len(parts) < 4:
95
+ parts.append(None)
96
+ return parts
97
+
98
+ for image_name in os.listdir(cr1_images_folder):
99
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
100
+ continue
101
+
102
+ image_path = os.path.join(cr1_images_folder, image_name)
103
+ base_name = os.path.splitext(image_name)[0]
104
+ output_file = os.path.join(output_json_folder, base_name + ".json")
105
+
106
+ if os.path.exists(output_file):
107
+ print(f"Skipped {image_name} (JSON file already exists)")
108
+ continue
109
+
110
+ with open(image_path, "rb") as f:
111
+ image_b64 = base64.b64encode(f.read()).decode()
112
+
113
+ data = {
114
+ "contents": [
115
+ {
116
+ "role": "user",
117
+ "parts": [
118
+ {"text": prompt},
119
+ {
120
+ "inline_data": {
121
+ "mime_type": "image/jpeg",
122
+ "data": image_b64
123
+ }
124
+ }
125
+ ]
126
+ }
127
+ ]
128
+ }
129
+
130
+ try:
131
+ response = requests.post(url, headers=headers, json=data)
132
+ response.raise_for_status()
133
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
134
+
135
+ # استخدام التعبير المنتظم الصحيح
136
+ match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
137
+ if match:
138
+ json_text = match.group(1)
139
+ result = json.loads(json_text)
140
+
141
+ # تقسيم العنوان إلى أجزاء منفصلة
142
+ if ركزها الرئيسي" in result and result["مركزها الرئيسي"]:
143
+ parts = split_address(result["مركزها الرئيسي"])
144
+ result["رقم المبنى"] = parts[0]
145
+ result["اسم الشارع"] = parts[1]
146
+ result["اسم الحي"] = parts[2]
147
+ result["الرقم الإضافي"] = parts[3]
148
+ else:
149
+ result["رقم المبنى"] = None
150
+ result["اسم الشارع"] = None
151
+ result["اسم الحي"] = None
152
+ result["الرقم الإضافي"] = None
153
+
154
+ with open(output_file, "w", encoding="utf-8") as f:
155
+ json.dump(result, f, ensure_ascii=False, indent=2)
156
+
157
+ print(f"✅ Processed: {image_name}")
158
+
159
+ else:
160
+ print(f"❌ Failed to extract JSON from: {image_name}")
161
+ print(response_text)
162
+
163
+ time.sleep(3) # ينتظر 3 ثواني قبل إرسال الصورة التالية
164
+
165
+ except Exception as e:
166
+ print(f"❌ Error processing image {image_name}: {e}")