abdullah-1111 commited on
Commit
7dd65f1
·
verified ·
1 Parent(s): 358a08a

Update json-CR4.py

Browse files
Files changed (1) hide show
  1. json-CR4.py +149 -145
json-CR4.py CHANGED
@@ -1,145 +1,149 @@
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
- Extract the following fields from the CR4 document image. Return both Arabic and English text where available:
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
- Return as JSON with keys:
43
- {
44
- "رقم_موحد": ...,
45
- "رقم_المنشأة": ...,
46
- "التاريخ": ...,
47
- "الاسم_التجاري": ...,
48
- "نوعها": ...,
49
- "جنسيتها": ...,
50
- "مدة_الشركة": ...,
51
- "تبدأ_من": ...,
52
- "تنتهي_في": ...,
53
- "مركزها_الرئيسي": ...,
54
- "هاتف": ...,
55
- "الرمز_البريدي": ...,
56
- "النشاط": ...,
57
- "رأس_المال": ...,
58
- "المديرون": ...,
59
- "سلطات_المدير": ...,
60
- "يشهد_مكتب_السجل": ...,
61
- "تم_تسجيل_المؤسسة": ...,
62
- "تنتهي_صلاحية_الشهادة": ...,
63
- "الإيصال_رقم": ...,
64
- "الإيصال_تاريخ": ...
65
- }
66
- If a field is missing, set it to null.
67
- """
68
- url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
69
- headers = {"Content-Type": "application/json"}
70
-
71
- def split_address(address):
72
- parts = [p.strip() for p in address.split("،")]
73
- while len(parts) < 4:
74
- parts.append(None)
75
- return parts
76
-
77
- for image_name in os.listdir(cr1_images_folder):
78
- if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
79
- continue
80
-
81
- image_path = os.path.join(cr1_images_folder, image_name)
82
- base_name = os.path.splitext(image_name)[0]
83
- output_file = os.path.join(output_json_folder, base_name + ".json")
84
-
85
- if os.path.exists(output_file):
86
- print(f"Skipped {image_name} (JSON file already exists)")
87
- continue
88
-
89
- with open(image_path, "rb") as f:
90
- image_b64 = base64.b64encode(f.read()).decode()
91
-
92
- data = {
93
- "contents": [
94
- {
95
- "role": "user",
96
- "parts": [
97
- {"text": prompt},
98
- {
99
- "inline_data": {
100
- "mime_type": "image/jpeg",
101
- "data": image_b64
102
- }
103
- }
104
- ]
105
- }
106
- ]
107
- }
108
-
109
- try:
110
- response = requests.post(url, headers=headers, json=data)
111
- response.raise_for_status()
112
- response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
113
-
114
- # استخدام التعبير المنتظم الصحيح
115
- match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
116
- if match:
117
- json_text = match.group(1)
118
- result = json.loads(json_text)
119
-
120
- # تقسيم العنوان إلى أجزاء منفصلة
121
- if "مركزها الرئيسي" in result and result["مركزها الرئيسي"]:
122
- parts = split_address(result["مركزها الرئيسي"])
123
- result["رقم المبنى"] = parts[0]
124
- result["اسم الشارع"] = parts[1]
125
- result["اسم الحي"] = parts[2]
126
- result["الرقم الإضافي"] = parts[3]
127
- else:
128
- result["رقم المبنى"] = None
129
- result["اسم الشارع"] = None
130
- result["اسم الحي"] = None
131
- result["الرقم الإضافي"] = None
132
-
133
- with open(output_file, "w", encoding="utf-8") as f:
134
- json.dump(result, f, ensure_ascii=False, indent=2)
135
-
136
- print(f"✅ Processed: {image_name}")
137
-
138
- else:
139
- print(f"❌ Failed to extract JSON from: {image_name}")
140
- print(response_text)
141
-
142
- time.sleep(3) # ينتظر 3 ثواني قبل إرسال الصورة التالية
143
-
144
- except Exception as e:
145
- 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
+ Extract the following fields from the CR4 document image. Return both Arabic and English text where available, and respond in JSON format using the English keys listed below.
17
+
18
+ Fields to extract:
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
+ Return as JSON with the following keys:
45
+ {
46
+ "unified_number": ...,
47
+ "establishment_number": ...,
48
+ "date": ...,
49
+ "company_name": ...,
50
+ "company_type": ...,
51
+ "nationality": ...,
52
+ "duration": ...,
53
+ "start_date": ...,
54
+ "end_date": ...,
55
+ "head_office": ...,
56
+ "phone": ...,
57
+ "postal_code": ...,
58
+ "business_activity": ...,
59
+ "capital": ...,
60
+ "managers": ...,
61
+ "manager_authority": ...,
62
+ "registry_office_city": ...,
63
+ "registered_in_city": ...,
64
+ "certificate_expiry_date": ...,
65
+ "receipt_number": ...,
66
+ "receipt_date": ...
67
+ }
68
+
69
+ If any field is missing from the document, set its value to null.
70
+ """
71
+
72
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
73
+ headers = {"Content-Type": "application/json"}
74
+
75
+ def split_address(address):
76
+ parts = [p.strip() for p in address.split("،")]
77
+ while len(parts) < 4:
78
+ parts.append(None)
79
+ return parts
80
+
81
+ for image_name in os.listdir(cr1_images_folder):
82
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
83
+ continue
84
+
85
+ image_path = os.path.join(cr1_images_folder, image_name)
86
+ base_name = os.path.splitext(image_name)[0]
87
+ output_file = os.path.join(output_json_folder, base_name + ".json")
88
+
89
+ if os.path.exists(output_file):
90
+ print(f"Skipped {image_name} (JSON file already exists)")
91
+ continue
92
+
93
+ with open(image_path, "rb") as f:
94
+ image_b64 = base64.b64encode(f.read()).decode()
95
+
96
+ data = {
97
+ "contents": [
98
+ {
99
+ "role": "user",
100
+ "parts": [
101
+ {"text": prompt},
102
+ {
103
+ "inline_data": {
104
+ "mime_type": "image/jpeg",
105
+ "data": image_b64
106
+ }
107
+ }
108
+ ]
109
+ }
110
+ ]
111
+ }
112
+
113
+ try:
114
+ response = requests.post(url, headers=headers, json=data)
115
+ response.raise_for_status()
116
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
117
+
118
+ # استخدام التعبير المنتظم الصحيح
119
+ match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
120
+ if match:
121
+ json_text = match.group(1)
122
+ result = json.loads(json_text)
123
+
124
+ # تقسيم العنوان إلى أجزاء منفصلة
125
+ if ركزها الرئيسي" in result and result["مركزها الرئيسي"]:
126
+ parts = split_address(result["مركزها الرئيسي"])
127
+ result["رقم المبنى"] = parts[0]
128
+ result["اسم الشارع"] = parts[1]
129
+ result["اسم الحي"] = parts[2]
130
+ result["الرقم الإضافي"] = parts[3]
131
+ else:
132
+ result["رقم المبنى"] = None
133
+ result["اسم الشارع"] = None
134
+ result["اسم الحي"] = None
135
+ result["الرقم الإضافي"] = None
136
+
137
+ with open(output_file, "w", encoding="utf-8") as f:
138
+ json.dump(result, f, ensure_ascii=False, indent=2)
139
+
140
+ print(f"✅ Processed: {image_name}")
141
+
142
+ else:
143
+ print(f"❌ Failed to extract JSON from: {image_name}")
144
+ print(response_text)
145
+
146
+ time.sleep(3) # ينتظر 3 ثواني قبل إرسال الصورة التالية
147
+
148
+ except Exception as e:
149
+ print(f"❌ Error processing image {image_name}: {e}")