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

Update json-CR5.py

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