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

Update json-CR7.py

Browse files
Files changed (1) hide show
  1. json-CR7.py +114 -112
json-CR7.py CHANGED
@@ -1,112 +1,114 @@
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}")
 
 
 
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
+ # Exact same prompt
20
+ prompt = """
21
+ Please extract the following fields from the CR7 commercial registration document image, all in Arabic only:
22
+
23
+ - اسم المنشأة
24
+ - نوع السجل
25
+ - حالة السجل
26
+ - الرقم الموحد للمنشأة
27
+ - رقم السجل التجاري
28
+ - اسم المالك
29
+ - نوع الكيان
30
+ - تاريخ الاصدار
31
+ - تاريخ الانتهاء
32
+ - قائمة المدراء
33
+ - المدينة
34
+ - الموقع الإلكتروني
35
+ - الانشطة التجارية
36
+
37
+ Please return the result as JSON with the exact keys below, and if any field is missing, set its value to null:
38
+
39
+ {
40
+ "establishment_name": null,
41
+ "registry_type": null,
42
+ "registry_status": null,
43
+ "unified_establishment_number": null,
44
+ "commercial_registry_number": null,
45
+ "owner_name": null,
46
+ "entity_type": null,
47
+ "issue_date": null,
48
+ "expiry_date": null,
49
+ "managers_list": null,
50
+ "city": null,
51
+ "website": null,
52
+ "business_activities": null
53
+ }
54
+ """
55
+
56
+ url = f"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key={API_KEY}"
57
+ headers = {"Content-Type": "application/json"}
58
+
59
+ # Iterate over all images
60
+ for image_name in os.listdir(cr1_images_folder):
61
+ if not image_name.lower().endswith(('.jpg', '.jpeg', '.png')):
62
+ continue
63
+
64
+ image_path = os.path.join(cr1_images_folder, image_name)
65
+ base_name = os.path.splitext(image_name)[0]
66
+ output_file = os.path.join(output_json_folder, base_name + ".json")
67
+
68
+ # Skip if JSON already exists
69
+ if os.path.exists(output_file):
70
+ print(f"Skipped {image_name} (JSON file already exists)")
71
+ continue
72
+
73
+ # Read image and convert to base64
74
+ with open(image_path, "rb") as f:
75
+ image_b64 = base64.b64encode(f.read()).decode()
76
+
77
+ # Send request to Gemini API
78
+ data = {
79
+ "contents": [
80
+ {
81
+ "role": "user",
82
+ "parts": [
83
+ {"text": prompt},
84
+ {
85
+ "inline_data": {
86
+ "mime_type": "image/jpeg",
87
+ "data": image_b64
88
+ }
89
+ }
90
+ ]
91
+ }
92
+ ]
93
+ }
94
+
95
+ try:
96
+ response = requests.post(url, headers=headers, json=data)
97
+ response.raise_for_status()
98
+ response_text = response.json()['candidates'][0]['content']['parts'][0]['text']
99
+
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
+ with open(output_file, "w", encoding="utf-8") as f:
106
+ json.dump(result, f, ensure_ascii=False, indent=2)
107
+
108
+ print(f" Processed: {image_name}")
109
+ else:
110
+ print(f"❌ Failed to extract JSON from: {image_name}")
111
+ print(response_text)
112
+
113
+ except Exception as e:
114
+ print(f"❌ Error processing image {image_name}: {e}")