abdullah-1111 commited on
Commit
2db08ff
·
verified ·
1 Parent(s): 69cea8e

Upload 14 files

Browse files
Files changed (14) hide show
  1. gemini_requestCR7.py +103 -0
  2. gemini_requestcr4.py +135 -0
  3. json-B.py +96 -0
  4. json-CR1.py +143 -0
  5. json-CR2.py +164 -0
  6. json-CR3.py +165 -0
  7. json-CR4.py +145 -0
  8. json-CR5.py +0 -0
  9. json-CR6.py +138 -0
  10. json-CR7.py +112 -0
  11. json-V2.py +97 -0
  12. json-V3.py +104 -0
  13. json-v1.py +92 -0
  14. orch.py +73 -0
gemini_requestCR7.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import json
3
+ import re
4
+ import requests
5
+ import os
6
+
7
+ # Your Gemini API key
8
+ API_KEY = "your_gemini_api_key_here"
9
+
10
+ #Path to the document image you want to extract data from
11
+ image_path = r"C:\Users\ASUS\Downloads\OneDrive_1_7-30-2025\CR7\CS015431_CR.jpg"
12
+
13
+ # قراءة الصورة وتحويلها إلى base64
14
+ with open(image_path, "rb") as f:
15
+ image_b64 = base64.b64encode(f.read()).decode()
16
+
17
+ prompt = """
18
+ يرجى استخراج الحقول التالية من مستند السجل التجاري (CR7) بالصورة، باللغة العربية فقط:
19
+
20
+ - اسم المنشأة
21
+ - نوع السجل
22
+ - حالة السجل
23
+ - الرقم الموحد للمنشأة
24
+ - رقم السجل التجاري
25
+ - اسم المالك
26
+ - نوع الكيان
27
+ - تاريخ الاصدار
28
+ - تاريخ الانتهاء
29
+ - قائمة المدراء
30
+ - المدينة
31
+ - الموقع الإلكتروني
32
+ - الانشطة التجارية
33
+
34
+ أرجو إعادة النتيجة بصيغة JSON بهذه المفاتيح فقط، وإذا أي حقل غير موجود فضع قيمته null:
35
+
36
+ {
37
+ "اسم المنشأة": null,
38
+ "نوع السجل": null,
39
+ "حالة السجل": null,
40
+ "الرقم الموحد للمنشأة": null,
41
+ "رقم السجل التجاري": null,
42
+ "اسم المالك": null,
43
+ "نوع الكيان": null,
44
+ "تاريخ الاصدار": null,
45
+ "تاريخ الانتهاء": null,
46
+ "قائمة المدراء": null,
47
+ "المدينة": null,
48
+ "الموقع الإلكتروني": null,
49
+ "الانشطة التجارية": null
50
+ }
51
+ """
52
+
53
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
54
+
55
+ headers = {
56
+ "Content-Type": "application/json"
57
+ }
58
+
59
+ data = {
60
+ "contents": [
61
+ {
62
+ "role": "user",
63
+ "parts": [
64
+ {"text": prompt},
65
+ {
66
+ "inline_data": {
67
+ "mime_type": "image/jpeg",
68
+ "data": image_b64
69
+ }
70
+ }
71
+ ]
72
+ }
73
+ ]
74
+ }
75
+
76
+ response = requests.post(url, headers=headers, json=data)
77
+
78
+ try:
79
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
80
+
81
+ match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
82
+ if match:
83
+ json_text = match.group(1)
84
+ result = json.loads(json_text)
85
+
86
+ # حفظ النتيجة بنفس اسم ملف الصورة وداخل نفس المجلد
87
+ folder = os.path.dirname(image_path)
88
+ base_name = os.path.splitext(os.path.basename(image_path))[0]
89
+ output_file = os.path.join(folder, base_name + ".json")
90
+
91
+ with open(output_file, "w", encoding="utf-8") as f:
92
+ json.dump(result, f, ensure_ascii=False, indent=2)
93
+
94
+ print(f"✅ تم حفظ النتيجة في ملف: {output_file}")
95
+ print(json.dumps(result, indent=2, ensure_ascii=False))
96
+ else:
97
+ print("❌ لم أتمكن من استخراج JSON نظيف من الرد:")
98
+ print(response_text)
99
+
100
+ except Exception as e:
101
+ print(f"❌ حدث خطأ أثناء المعالجة: {e}")
102
+ print("🔴 الرد الكامل من Gemini:")
103
+ print(response.text)
gemini_requestcr4.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import json
3
+ import re
4
+ import requests
5
+ import os
6
+
7
+ # Your Gemini API key
8
+ API_KEY = "your_gemini_api_key_here"
9
+
10
+
11
+ #Path to the document image you want to extract data from
12
+ image_path = r"C:\Users\ASUS\Downloads\CR_OCR_Cls.v4-original_images.folder\train\CR4\CS000130_CR_jpg.rf.b2528e60546ec399c3088ac69c6a66e2.jpg"
13
+
14
+ with open(image_path, "rb") as f:
15
+ image_b64 = base64.b64encode(f.read()).decode()
16
+
17
+ prompt = """
18
+ Extract the following fields from the CR4 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
+ وتاريخ
43
+
44
+ Return as JSON with keys:
45
+ {
46
+ "رقم_موحد": ...,
47
+ "رقم_المنشأة": ...,
48
+ "التاريخ": ...,
49
+ "الاسم_التجاري": ...,
50
+ "نوعها": ...,
51
+ "جنسيتها": ...,
52
+ "مدة_الشركة": ...,
53
+ "تبدأ_من": ...,
54
+ "تنتهي_في": ...,
55
+ "مركزها_الرئيسي": ...,
56
+ "هاتف": ...,
57
+ "الرمز_البريدي": ...,
58
+ "النشاط": ...,
59
+ "رأس_المال": ...,
60
+ "المديرون": ...,
61
+ "سلطات_المدير": ...,
62
+ "يشهد_مكتب_السجل": ...,
63
+ "تم_تسجيل_المؤسسة": ...,
64
+ "تنتهي_صلاحية_الشهادة": ...,
65
+ "الإيصال_رقم": ...,
66
+ "الإيصال_تاريخ": ...
67
+ }
68
+ If a field is missing, set it to null.
69
+ """
70
+
71
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
72
+
73
+ headers = {
74
+ "Content-Type": "application/json"
75
+ }
76
+
77
+ data = {
78
+ "contents": [
79
+ {
80
+ "role": "user",
81
+ "parts": [
82
+ {"text": prompt},
83
+ {
84
+ "inline_data": {
85
+ "mime_type": "image/jpeg",
86
+ "data": image_b64
87
+ }
88
+ }
89
+ ]
90
+ }
91
+ ]
92
+ }
93
+
94
+ response = requests.post(url, headers=headers, json=data)
95
+
96
+ try:
97
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
98
+
99
+ # استخراج JSON من النص
100
+ match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
101
+ if match:
102
+ json_text = match.group(1)
103
+ result = json.loads(json_text)
104
+
105
+ base_name = os.path.splitext(os.path.basename(image_path))[0]
106
+ folder = os.path.dirname(image_path)
107
+ json_path = os.path.join(folder, f"{base_name}.json")
108
+
109
+ # إذا الملف موجود نقرأه ونضيف عليه
110
+ if os.path.exists(json_path):
111
+ with open(json_path, "r", encoding="utf-8") as f:
112
+ try:
113
+ existing_data = json.load(f)
114
+ if not isinstance(existing_data, list):
115
+ existing_data = [existing_data]
116
+ except json.JSONDecodeError:
117
+ existing_data = []
118
+ else:
119
+ existing_data = []
120
+
121
+ existing_data.append(result)
122
+
123
+ with open(json_path, "w", encoding="utf-8") as f:
124
+ json.dump(existing_data, f, ensure_ascii=False, indent=2)
125
+
126
+ print(f"✅ تم حفظ النتيجة في الملف: {json_path}")
127
+ print(json.dumps(result, indent=2, ensure_ascii=False))
128
+ else:
129
+ print("❌ لم أتمكن من استخراج JSON نظيف من الرد:")
130
+ print(response_text)
131
+
132
+ except Exception as e:
133
+ print(f"❌ حدث خطأ أثناء المعالجة: {e}")
134
+ print("الرد الكامل من Gemini:")
135
+ print(response.text)
json-B.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\CR1"
12
+ # مجلد إخراج ملفات JSON
13
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR1\cr1_json"
14
+
15
+ # Ensure output folder exists
16
+ os.makedirs(output_json_folder, exist_ok=True)
17
+
18
+ # Exact same prompt
19
+ prompt = """
20
+ Please extract the following fields in Arabic and English from the government registration document image:
21
+ - License Number
22
+ - Owner's Name
23
+ - ISIC Classification
24
+ - Detailed Activity
25
+ - Municipality
26
+ - Sub-Municipality
27
+ - District
28
+ - Street
29
+ - Shop's Total Area
30
+
31
+ Return the result in a JSON format with these keys:
32
+ en_license_number, en_owner_name, en_isic_classification, en_detailed_activity, en_municipality, en_sub_municipality, en_district, en_street, en_shop_total_area,
33
+ ar_license_number, ar_owner_name, ar_isic_classification, ar_detailed_activity, ar_municipality, ar_sub_municipality, ar_district, ar_street, ar_shop_total_area
34
+
35
+ If a field is missing, return null.
36
+ """
37
+
38
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
39
+ headers = {"Content-Type": "application/json"}
40
+
41
+ # Iterate over all images
42
+ for image_name in os.listdir(cr1_images_folder):
43
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
44
+ continue
45
+
46
+ image_path = os.path.join(cr1_images_folder, image_name)
47
+ base_name = os.path.splitext(image_name)[0]
48
+ output_file = os.path.join(output_json_folder, base_name + ".json")
49
+
50
+ # Skip if JSON already exists
51
+ if os.path.exists(output_file):
52
+ print(f"Skipped {image_name} (JSON file already exists)")
53
+ continue
54
+
55
+ # Read image and convert to base64
56
+ with open(image_path, "rb") as f:
57
+ image_b64 = base64.b64encode(f.read()).decode()
58
+
59
+ # Send request to Gemini API
60
+ data = {
61
+ "contents": [
62
+ {
63
+ "role": "user",
64
+ "parts": [
65
+ {"text": prompt},
66
+ {
67
+ "inline_data": {
68
+ "mime_type": "image/jpeg",
69
+ "data": image_b64
70
+ }
71
+ }
72
+ ]
73
+ }
74
+ ]
75
+ }
76
+
77
+ try:
78
+ response = requests.post(url, headers=headers, json=data)
79
+ response.raise_for_status()
80
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
81
+
82
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
83
+ if match:
84
+ json_text = match.group(1)
85
+ result = json.loads(json_text)
86
+
87
+ with open(output_file, "w", encoding="utf-8") as f:
88
+ json.dump(result, f, ensure_ascii=False, indent=2)
89
+
90
+ print(f"✅ Processed: {image_name}")
91
+ else:
92
+ print(f"❌ Failed to extract JSON from: {image_name}")
93
+ print(response_text)
94
+
95
+ except Exception as e:
96
+ print(f"❌ Error processing image {image_name}: {e}")
json-CR1.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\CR1"
12
+ # مجلد إخراج ملفات JSON
13
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR1\cr1_json"
14
+
15
+ # Ensure output folder exists
16
+ os.makedirs(output_json_folder, exist_ok=True)
17
+
18
+ # Exact same prompt
19
+ prompt = """
20
+ Please extract the following fields from the CR1 commercial registration document image, all in Arabic only:
21
+
22
+ - Unified number
23
+ - Establishment number
24
+ - Commercial name of the institution
25
+ - Its main center
26
+ - Phone
27
+ - Postal code
28
+ - Trader name
29
+ - Nationality
30
+ - Date of birth
31
+ - Civil registry number - residence
32
+ - Its date
33
+ - Its source
34
+ - Passport number
35
+ - Its date
36
+ - Issuer
37
+ - Activity
38
+ - Capital
39
+ - Name of the manager or authorized agent
40
+ - Nationality
41
+ - Date of birth
42
+ - Civil registry number - residence
43
+ - Its date
44
+ - Its source
45
+ - Certified by the commercial registration office in the city
46
+ - That the above-mentioned institution is registered in the city
47
+ - Certificates expire on
48
+ - Receipt number
49
+ - Date
50
+
51
+ Please return the result as JSON with these exact keys only, and if any field is missing, set its value to null:
52
+
53
+ {
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
+ }
83
+ """
84
+
85
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
86
+ headers = {"Content-Type": "application/json"}
87
+
88
+ # Iterate over all images
89
+ for image_name in os.listdir(cr1_images_folder):
90
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
91
+ continue
92
+
93
+ image_path = os.path.join(cr1_images_folder, image_name)
94
+ base_name = os.path.splitext(image_name)[0]
95
+ output_file = os.path.join(output_json_folder, base_name + ".json")
96
+
97
+ # Skip if JSON already exists
98
+ if os.path.exists(output_file):
99
+ print(f"Skipped {image_name} (JSON file already exists)")
100
+ continue
101
+
102
+ # Read image and convert to base64
103
+ with open(image_path, "rb") as f:
104
+ image_b64 = base64.b64encode(f.read()).decode()
105
+
106
+ # Send request to Gemini API
107
+ data = {
108
+ "contents": [
109
+ {
110
+ "role": "user",
111
+ "parts": [
112
+ {"text": prompt},
113
+ {
114
+ "inline_data": {
115
+ "mime_type": "image/jpeg",
116
+ "data": image_b64
117
+ }
118
+ }
119
+ ]
120
+ }
121
+ ]
122
+ }
123
+
124
+ try:
125
+ response = requests.post(url, headers=headers, json=data)
126
+ response.raise_for_status()
127
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
128
+
129
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
130
+ if match:
131
+ json_text = match.group(1)
132
+ result = json.loads(json_text)
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
+ else:
139
+ print(f"❌ Failed to extract JSON from: {image_name}")
140
+ print(response_text)
141
+
142
+ except Exception as e:
143
+ print(f"❌ Error processing image {image_name}: {e}")
json-CR2.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}")
json-CR3.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 CR3 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
+ مصدره
43
+ سلطات المدير
44
+ يشهد مكتب السجل التجاري بمدينة
45
+ بأنه تم تسجيل المؤسسة المذكورة أعلاة بمدينة
46
+ وتنتهي صلاحية الشهادات في
47
+ بموجب الإيصال رقم
48
+ وتاريخ
49
+ مدير السجل التجاري
50
+
51
+ Return as JSON with keys:
52
+ {
53
+ "الرقم": ...,
54
+ "التاريخ": ...,
55
+ "الرقم_الموحد_للمنشأة": ...,
56
+ "اسم_التاجر": ...,
57
+ "الجنسية": ...,
58
+ "تاريخ_الميلاد": ...,
59
+ "رقم_السجل_المدني_الإقامة": ...,
60
+ "تاريخه": ...,
61
+ "مصدرة": ...,
62
+ "مركزها_الرئيسي": ...,
63
+ "هاتف": ...,
64
+ "الرمز_البريدي": ...,
65
+ "رقم_سجل_المركز_الرئيسي": ...,
66
+ "الاسم_التجاري_للفرع": ...,
67
+ "العنوان": ...,
68
+ "الرمز_البريدي_الفرع": ...,
69
+ "الهاتف_الفرع": ...,
70
+ "النشاط": ...,
71
+ "رأس_المال": ...,
72
+ "اسم_المدير_او_الوكيل_المفوض": ...,
73
+ "الجنسية_المدير": ...,
74
+ "تاريخ_ميلاد_المدير": ...,
75
+ "رقم_السجل_المدني_الإقامة_المدير": ...,
76
+ "تاريخه_المدير": ...,
77
+ "مصدره_المدير": ...,
78
+ "سلطات_المدير": ...,
79
+ "يشهد_مكتب_السجل": ...,
80
+ "تم_تسجيل_المؤسسة": ...,
81
+ "تنتهي_صلاحية_الشهادة": ...,
82
+ "الإيصال_رقم": ...,
83
+ "الإيصال_تاريخ": ...,
84
+ "مدير_السجل_التجاري": ...
85
+ }
86
+ If a field is missing, set it to null.
87
+ """
88
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
89
+ headers = {"Content-Type": "application/json"}
90
+
91
+ def split_address(address):
92
+ parts = [p.strip() for p in address.split("،")]
93
+ while len(parts) < 4:
94
+ parts.append(None)
95
+ return parts
96
+
97
+ for image_name in os.listdir(cr1_images_folder):
98
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
99
+ continue
100
+
101
+ image_path = os.path.join(cr1_images_folder, image_name)
102
+ base_name = os.path.splitext(image_name)[0]
103
+ output_file = os.path.join(output_json_folder, base_name + ".json")
104
+
105
+ if os.path.exists(output_file):
106
+ print(f"Skipped {image_name} (JSON file already exists)")
107
+ continue
108
+
109
+ with open(image_path, "rb") as f:
110
+ image_b64 = base64.b64encode(f.read()).decode()
111
+
112
+ data = {
113
+ "contents": [
114
+ {
115
+ "role": "user",
116
+ "parts": [
117
+ {"text": prompt},
118
+ {
119
+ "inline_data": {
120
+ "mime_type": "image/jpeg",
121
+ "data": image_b64
122
+ }
123
+ }
124
+ ]
125
+ }
126
+ ]
127
+ }
128
+
129
+ try:
130
+ response = requests.post(url, headers=headers, json=data)
131
+ response.raise_for_status()
132
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
133
+
134
+ # استخدام التعبير المنتظم الصحيح
135
+ match = re.search(r"```json\s*(\{.*?\})\s*```", response_text, re.DOTALL)
136
+ if match:
137
+ json_text = match.group(1)
138
+ result = json.loads(json_text)
139
+
140
+ # تقسيم العنوان إلى أجزاء منفصلة
141
+ if "مركزها الرئيسي" in result and result["مركزها الرئيسي"]:
142
+ parts = split_address(result["مركزها الرئيسي"])
143
+ result["رقم المبنى"] = parts[0]
144
+ result["اسم الشارع"] = parts[1]
145
+ result["اسم الحي"] = parts[2]
146
+ result["الرقم الإضافي"] = parts[3]
147
+ else:
148
+ result["رقم المبنى"] = None
149
+ result["اسم الشارع"] = None
150
+ result["اسم الحي"] = None
151
+ result["الرقم الإضافي"] = None
152
+
153
+ with open(output_file, "w", encoding="utf-8") as f:
154
+ json.dump(result, f, ensure_ascii=False, indent=2)
155
+
156
+ print(f"✅ Processed: {image_name}")
157
+
158
+ else:
159
+ print(f"❌ Failed to extract JSON from: {image_name}")
160
+ print(response_text)
161
+
162
+ time.sleep(3) # ينتظر 3 ثواني قبل إرسال الصورة التالية
163
+
164
+ except Exception as e:
165
+ print(f"❌ Error processing image {image_name}: {e}")
json-CR4.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}")
json-CR5.py ADDED
File without changes
json-CR6.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}")
json-CR7.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\CR1"
12
+ # مجلد إخراج ملفات JSON
13
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR1\cr1_json"
14
+
15
+ # Ensure output folder exists
16
+ os.makedirs(output_json_folder, exist_ok=True)
17
+
18
+ # Exact same prompt
19
+ prompt = """
20
+ يرجى استخراج الحقول التالية من مستند السجل التجاري (CR7) بالصورة، باللغة العربية فقط:
21
+
22
+ - اسم المنشأة
23
+ - نوع السجل
24
+ - حالة السجل
25
+ - الرقم الموحد للمنشأة
26
+ - رقم السجل التجاري
27
+ - اسم المالك
28
+ - نوع الكيان
29
+ - تاريخ الاصدار
30
+ - تاريخ الانتهاء
31
+ - قائمة المدراء
32
+ - المدينة
33
+ - الموقع الإلكتروني
34
+ - الانشطة التجارية
35
+
36
+ أرجو إعادة النتيجة بصيغة JSON بهذه المفاتيح فقط، وإذا أي حقل غير موجود فضع قيمته null:
37
+
38
+ {
39
+ "اسم المنشأة": null,
40
+ "نوع السجل": null,
41
+ "حالة السجل": null,
42
+ "الرقم الموحد للمنشأة": null,
43
+ "رقم السجل التجاري": null,
44
+ "اسم المالك": null,
45
+ "نوع الكيان": null,
46
+ "تاريخ الاصدار": null,
47
+ "تاريخ الانتهاء": null,
48
+ "قائمة المدراء": null,
49
+ "المدينة": null,
50
+ "الموقع الإلكتروني": null,
51
+ "الانشطة التجارية": null
52
+ }
53
+ """
54
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
55
+ headers = {"Content-Type": "application/json"}
56
+
57
+ # Iterate over all images
58
+ for image_name in os.listdir(cr1_images_folder):
59
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
60
+ continue
61
+
62
+ image_path = os.path.join(cr1_images_folder, image_name)
63
+ base_name = os.path.splitext(image_name)[0]
64
+ output_file = os.path.join(output_json_folder, base_name + ".json")
65
+
66
+ # Skip if JSON already exists
67
+ if os.path.exists(output_file):
68
+ print(f"Skipped {image_name} (JSON file already exists)")
69
+ continue
70
+
71
+ # Read image and convert to base64
72
+ with open(image_path, "rb") as f:
73
+ image_b64 = base64.b64encode(f.read()).decode()
74
+
75
+ # Send request to Gemini API
76
+ data = {
77
+ "contents": [
78
+ {
79
+ "role": "user",
80
+ "parts": [
81
+ {"text": prompt},
82
+ {
83
+ "inline_data": {
84
+ "mime_type": "image/jpeg",
85
+ "data": image_b64
86
+ }
87
+ }
88
+ ]
89
+ }
90
+ ]
91
+ }
92
+
93
+ try:
94
+ response = requests.post(url, headers=headers, json=data)
95
+ response.raise_for_status()
96
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
97
+
98
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
99
+ if match:
100
+ json_text = match.group(1)
101
+ result = json.loads(json_text)
102
+
103
+ with open(output_file, "w", encoding="utf-8") as f:
104
+ json.dump(result, f, ensure_ascii=False, indent=2)
105
+
106
+ print(f"✅ Processed: {image_name}")
107
+ else:
108
+ print(f"❌ Failed to extract JSON from: {image_name}")
109
+ print(response_text)
110
+
111
+ except Exception as e:
112
+ print(f"❌ Error processing image {image_name}: {e}")
json-V2.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\CR1"
12
+ # مجلد إخراج ملفات JSON
13
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR1\cr1_json"
14
+
15
+ # Ensure output folder exists
16
+ os.makedirs(output_json_folder, exist_ok=True)
17
+
18
+ # Exact same prompt
19
+ prompt = """
20
+ Please extract the following fields in Arabic and English from the tax document image:
21
+ Taxpayer Name
22
+ VAT Registration Number
23
+ Effective Registration Date
24
+ Taxpayer Address
25
+ CR/License
26
+ Contract/ID No
27
+ Tax period
28
+ First Filing due date
29
+
30
+ Return the result in a JSON format with these keys:
31
+ en_taxpayer_name, en_vat_registration_number, en_effective_registration_date, en_taxpayer_address,
32
+ en_cr_license, en_contract_id_no, en_tax_period, en_first_filing_due_date,
33
+ ar_taxpayer_name, ar_vat_registration_number, ar_effective_registration_date, ar_taxpayer_address,
34
+ ar_cr_license, ar_contract_id_no, ar_tax_period, ar_first_filing_due_date
35
+
36
+ If a field is missing, return null.
37
+ """
38
+
39
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
40
+ headers = {"Content-Type": "application/json"}
41
+
42
+ # Iterate over all images
43
+ for image_name in os.listdir(cr1_images_folder):
44
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
45
+ continue
46
+
47
+ image_path = os.path.join(cr1_images_folder, image_name)
48
+ base_name = os.path.splitext(image_name)[0]
49
+ output_file = os.path.join(output_json_folder, base_name + ".json")
50
+
51
+ # Skip if JSON already exists
52
+ if os.path.exists(output_file):
53
+ print(f"Skipped {image_name} (JSON file already exists)")
54
+ continue
55
+
56
+ # Read image and convert to base64
57
+ with open(image_path, "rb") as f:
58
+ image_b64 = base64.b64encode(f.read()).decode()
59
+
60
+ # Send request to Gemini API
61
+ data = {
62
+ "contents": [
63
+ {
64
+ "role": "user",
65
+ "parts": [
66
+ {"text": prompt},
67
+ {
68
+ "inline_data": {
69
+ "mime_type": "image/jpeg",
70
+ "data": image_b64
71
+ }
72
+ }
73
+ ]
74
+ }
75
+ ]
76
+ }
77
+
78
+ try:
79
+ response = requests.post(url, headers=headers, json=data)
80
+ response.raise_for_status()
81
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
82
+
83
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
84
+ if match:
85
+ json_text = match.group(1)
86
+ result = json.loads(json_text)
87
+
88
+ with open(output_file, "w", encoding="utf-8") as f:
89
+ json.dump(result, f, ensure_ascii=False, indent=2)
90
+
91
+ print(f"✅ Processed: {image_name}")
92
+ else:
93
+ print(f"❌ Failed to extract JSON from: {image_name}")
94
+ print(response_text)
95
+
96
+ except Exception as e:
97
+ print(f"❌ Error processing image {image_name}: {e}")
json-V3.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\CR1"
12
+ # مجلد إخراج ملفات JSON
13
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR1\cr1_json"
14
+
15
+ # Ensure output folder exists
16
+ os.makedirs(output_json_folder, exist_ok=True)
17
+
18
+ # Exact same prompt
19
+ prompt = """
20
+ استخرج الحقول التالية من مستند باللغة العربية فقط، وأرجعها بصيغة JSON:
21
+
22
+ 1. اسم المكلف
23
+ 2. عنوان المركز الرئيسي
24
+ 3. المدينة
25
+ 4. الحي
26
+ 5. صندوق البريد
27
+ 6. الرمز البريدي
28
+ 7. الهاتف
29
+
30
+ الصيغة المطلوبة:
31
+
32
+ {
33
+ "اسم المكلف": "...",
34
+ "عنوان المركز الرئيسي": "...",
35
+ "المدينة": "...",
36
+ "الحي": "...",
37
+ "صندوق البريد": "...",
38
+ "الرمز البريدي": "...",
39
+ "الهاتف": "..."
40
+ }
41
+
42
+ إذا لم يوجد حقل، أرجعه كـ null.
43
+ """
44
+
45
+
46
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
47
+ headers = {"Content-Type": "application/json"}
48
+
49
+ # Iterate over all images
50
+ for image_name in os.listdir(cr1_images_folder):
51
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
52
+ continue
53
+
54
+ image_path = os.path.join(cr1_images_folder, image_name)
55
+ base_name = os.path.splitext(image_name)[0]
56
+ output_file = os.path.join(output_json_folder, base_name + ".json")
57
+
58
+ # Skip if JSON already exists
59
+ if os.path.exists(output_file):
60
+ print(f"Skipped {image_name} (JSON file already exists)")
61
+ continue
62
+
63
+ # Read image and convert to base64
64
+ with open(image_path, "rb") as f:
65
+ image_b64 = base64.b64encode(f.read()).decode()
66
+
67
+ # Send request to Gemini API
68
+ data = {
69
+ "contents": [
70
+ {
71
+ "role": "user",
72
+ "parts": [
73
+ {"text": prompt},
74
+ {
75
+ "inline_data": {
76
+ "mime_type": "image/jpeg",
77
+ "data": image_b64
78
+ }
79
+ }
80
+ ]
81
+ }
82
+ ]
83
+ }
84
+
85
+ try:
86
+ response = requests.post(url, headers=headers, json=data)
87
+ response.raise_for_status()
88
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
89
+
90
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
91
+ if match:
92
+ json_text = match.group(1)
93
+ result = json.loads(json_text)
94
+
95
+ with open(output_file, "w", encoding="utf-8") as f:
96
+ json.dump(result, f, ensure_ascii=False, indent=2)
97
+
98
+ print(f"✅ Processed: {image_name}")
99
+ else:
100
+ print(f"❌ Failed to extract JSON from: {image_name}")
101
+ print(response_text)
102
+
103
+ except Exception as e:
104
+ print(f"❌ Error processing image {image_name}: {e}")
json-v1.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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\CR1"
12
+ # مجلد إخراج ملفات JSON
13
+ output_json_folder = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch\classified\CR1\cr1_json"
14
+
15
+ # Ensure output folder exists
16
+ os.makedirs(output_json_folder, exist_ok=True)
17
+
18
+ # Exact same prompt
19
+ prompt = """
20
+ Please extract the following fields in Arabic and English from the tax registration document image:
21
+ Taxpayer Name
22
+ VAT Registration Number
23
+ Effective Registration Date
24
+ Taxpayer Address
25
+
26
+ Return the result in a JSON format with these keys:
27
+ en_taxpayer_name, en_vat_registration_number, en_effective_registration_date, en_taxpayer_address,
28
+ ar_taxpayer_name, ar_vat_registration_number, ar_effective_registration_date, ar_taxpayer_address
29
+
30
+ If a field is missing, return null.
31
+ """
32
+
33
+
34
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
35
+ headers = {"Content-Type": "application/json"}
36
+
37
+ # Iterate over all images
38
+ for image_name in os.listdir(cr1_images_folder):
39
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
40
+ continue
41
+
42
+ image_path = os.path.join(cr1_images_folder, image_name)
43
+ base_name = os.path.splitext(image_name)[0]
44
+ output_file = os.path.join(output_json_folder, base_name + ".json")
45
+
46
+ # Skip if JSON already exists
47
+ if os.path.exists(output_file):
48
+ print(f"Skipped {image_name} (JSON file already exists)")
49
+ continue
50
+
51
+ # Read image and convert to base64
52
+ with open(image_path, "rb") as f:
53
+ image_b64 = base64.b64encode(f.read()).decode()
54
+
55
+ # Send request to Gemini API
56
+ data = {
57
+ "contents": [
58
+ {
59
+ "role": "user",
60
+ "parts": [
61
+ {"text": prompt},
62
+ {
63
+ "inline_data": {
64
+ "mime_type": "image/jpeg",
65
+ "data": image_b64
66
+ }
67
+ }
68
+ ]
69
+ }
70
+ ]
71
+ }
72
+
73
+ try:
74
+ response = requests.post(url, headers=headers, json=data)
75
+ response.raise_for_status()
76
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
77
+
78
+ match = re.search(r"```json\s*(\{.*\})\s*```", response_text, re.DOTALL)
79
+ if match:
80
+ json_text = match.group(1)
81
+ result = json.loads(json_text)
82
+
83
+ with open(output_file, "w", encoding="utf-8") as f:
84
+ json.dump(result, f, ensure_ascii=False, indent=2)
85
+
86
+ print(f"✅ Processed: {image_name}")
87
+ else:
88
+ print(f"❌ Failed to extract JSON from: {image_name}")
89
+ print(response_text)
90
+
91
+ except Exception as e:
92
+ print(f"❌ Error processing image {image_name}: {e}")
orch.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from ultralytics import YOLO
4
+
5
+ # =======================================
6
+ # 🟡🔧 User-configurable settings
7
+ # =======================================
8
+
9
+ # 📁 Folder containing images to classify
10
+ INPUT_FOLDER = r"C:\Users\ASUS\OneDrive - Binder\Desktop\test.orch" # ← Modify this path
11
+
12
+ # 📁 Folder to save classified images
13
+ OUTPUT_BASE = os.path.join(INPUT_FOLDER, "classified") # ← Automatically inside input folder
14
+
15
+ # 📦 Path to YOLOv8 classification model
16
+ MODEL_PATH = r"C:\Users\ASUS\Downloads\best.pt" # ← Modify this path
17
+
18
+ # ✅ Allowed classes only
19
+ ALLOWED_CLASSES = {"CR1", "CR2", "CR3", "CR4", "CR5", "CR6", "CR7", "b1", "b2", "b3", "b4", "v1", "v2", "v3"}
20
+
21
+ # =======================================
22
+ # 🚀 Load the model
23
+ # =======================================
24
+ model = YOLO(MODEL_PATH)
25
+
26
+ # =======================================
27
+ # 🧠 Classify a single image
28
+ # =======================================
29
+ def classify_image_yolo(image_path):
30
+ try:
31
+ results = model(image_path, verbose=False)[0]
32
+ class_id = int(results.probs.top1)
33
+ class_name = model.names.get(class_id, "others")
34
+ return class_name
35
+ except Exception as e:
36
+ print(f"❌ Error classifying image {image_path}: {e}")
37
+ return "others"
38
+
39
+ # =======================================
40
+ # 📂 Classify and move images
41
+ # =======================================
42
+ processed_files = set()
43
+
44
+ for filename in os.listdir(INPUT_FOLDER):
45
+ file_path = os.path.join(INPUT_FOLDER, filename)
46
+
47
+ if not os.path.isfile(file_path):
48
+ continue
49
+
50
+ if filename in processed_files:
51
+ continue
52
+
53
+ class_name = classify_image_yolo(file_path)
54
+
55
+ # ✅ Check if class is allowed, otherwise assign to "others"
56
+ if class_name not in ALLOWED_CLASSES:
57
+ class_name = "others"
58
+
59
+ # Create class folder if not exists
60
+ output_folder = os.path.join(OUTPUT_BASE, class_name)
61
+ os.makedirs(output_folder, exist_ok=True)
62
+
63
+ destination_path = os.path.join(output_folder, filename)
64
+
65
+ # Avoid duplicate images
66
+ if not os.path.exists(destination_path):
67
+ shutil.move(file_path, destination_path)
68
+ print(f"✅ Moved image {filename} to [{class_name}]")
69
+ processed_files.add(filename)
70
+ else:
71
+ print(f"⚠️ Image {filename} already exists in [{class_name}], skipped")
72
+
73
+ print("🎉 Finished classifying images using YOLOv8 Classification!")