mhammad commited on
Commit
e890a52
·
verified ·
1 Parent(s): cfb6add

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. 5.py +224 -224
  2. app.log +0 -0
  3. docs/your_data.csv +0 -0
  4. flagged/log.csv +2 -2
  5. requirements.txt +3 -3
  6. run.bat +2 -2
5.py CHANGED
@@ -1,224 +1,224 @@
1
- import threading
2
- import time
3
- import openai
4
- import gradio as gr
5
- import csv
6
- import re
7
- import os
8
- from datetime import datetime, timedelta
9
- from gtts import gTTS
10
- from queue import Queue
11
-
12
- # Set your OpenAI API key
13
- openai.api_key = 'YOUR_API_KEY'
14
-
15
- # Global TTS queue
16
- tts_queue = Queue()
17
-
18
- # Load data from the CSV file when the application starts
19
- data = None
20
-
21
- def load_training_data():
22
- global data
23
- if data is None:
24
- data = {}
25
- with open("docs/your_data.csv", "r", encoding="utf-8-sig") as csvfile:
26
- reader = csv.DictReader(csvfile)
27
- for row in reader:
28
- plate_number = row.get("رقم المركبة", "").strip()
29
- company_name = row.get("اسم الشركه", "").strip()
30
- date = row.get("تاريخ الدخول", "").strip()
31
-
32
- if plate_number not in data:
33
- data[plate_number] = []
34
- data[plate_number].append(row)
35
-
36
- if company_name not in data:
37
- data[company_name] = []
38
- data[company_name].append(row)
39
-
40
- if date not in data:
41
- data[date] = []
42
- data[date].append(row)
43
-
44
- def parse_date(date_str):
45
- return datetime.strptime(date_str, "%d.%m.%Y")
46
-
47
- def get_week_range(date_str):
48
- current_date = parse_date(date_str)
49
- days_to_subtract = (current_date.weekday() + 2) % 7
50
- start_of_week = current_date - timedelta(days=days_to_subtract)
51
- end_of_week = start_of_week + timedelta(days=6)
52
- return start_of_week, end_of_week
53
-
54
- def text_to_speech(text):
55
- try:
56
- speech = gTTS(text=text, lang='ar', slow=False)
57
- filename = f"text_to_speech_{int(time.time())}.mp3"
58
- filepath = os.path.join("static", filename)
59
- speech.save(filepath)
60
- return filepath
61
- except Exception as e:
62
- print("Exception:", str(e))
63
- return None
64
-
65
- def calculate_weekly_total(date_str):
66
- load_training_data()
67
- try:
68
- input_date = parse_date(date_str)
69
- except ValueError:
70
- return "Invalid date format. Please enter a date in the format dd.mm.yyyy."
71
- start_of_week, end_of_week = get_week_range(date_str)
72
- weekly_total = 0
73
- for date_key in data.keys():
74
- try:
75
- record_date = parse_date(date_key)
76
- if start_of_week <= record_date <= end_of_week:
77
- for record in data[date_key]:
78
- report = record.get("تقرير نهائي", "")
79
- if "شغل" in report:
80
- money_values = re.findall(r'شغل\s*(\d+)\s*شيكل', report)
81
- else:
82
- money_values = re.findall(r'(\d+)\s*شيكل', report)
83
- money_values = [int(value) for value in money_values]
84
- weekly_total += sum(money_values)
85
- except ValueError:
86
- continue
87
- return weekly_total
88
-
89
- def calculate_weekly_cash_total(date_str):
90
- load_training_data()
91
- try:
92
- input_date = parse_date(date_str)
93
- except ValueError:
94
- return "Invalid date format. Please enter a date in the format dd.mm.yyyy."
95
- start_of_week, end_of_week = get_week_range(date_str)
96
- weekly_cash_total = 0
97
- for date_key in data.keys():
98
- try:
99
- record_date = parse_date(date_key)
100
- if start_of_week <= record_date <= end_of_week:
101
- for record in data[date_key]:
102
- plate_number = record.get("رقم المركبة", "")
103
- if "كاش" in plate_number:
104
- report = record.get("تقرير نهائي", "")
105
- money_values = re.findall(r'(\d+)\s*شيكل', report)
106
- money_values = [int(value) for value in money_values]
107
- weekly_cash_total += sum(money_values)
108
- except ValueError:
109
- continue
110
- return weekly_cash_total
111
-
112
- def search_partial_matches(input_text):
113
- load_training_data()
114
- input_text = input_text.strip()
115
- matching_records = {}
116
- for key in data.keys():
117
- if input_text in key:
118
- matching_records[key] = data[key]
119
- return matching_records
120
-
121
- def calculate_total_for_period(start_date_str, end_date_str):
122
- load_training_data()
123
- try:
124
- start_date = parse_date(start_date_str)
125
- end_date = parse_date(end_date_str)
126
- except ValueError:
127
- return "Invalid date format. Please enter dates in the format dd.mm.yyyy."
128
- total_amount = 0
129
- for date_key in data.keys():
130
- try:
131
- record_date = parse_date(date_key)
132
- if start_date <= record_date <= end_date:
133
- for record in data[date_key]:
134
- report = record.get("تقرير نهائي", "")
135
- if "شغل" in report:
136
- money_values = re.findall(r'شغل\s*(\d+)\s*شيكل', report)
137
- else:
138
- money_values = re.findall(r'(\d+)\s*شيكل', report)
139
- money_values = [int(value) for value in money_values]
140
- total_amount += sum(money_values)
141
- except ValueError:
142
- continue
143
- return total_amount
144
-
145
- def chatbot(input_text, start_date_str="", end_date_str="", enable_voice=False):
146
- if start_date_str and end_date_str:
147
- total_for_period = calculate_total_for_period(start_date_str, end_date_str)
148
- return (f"Total amount from {start_date_str} to {end_date_str}: {total_for_period} شيكل", "", "", None)
149
- else:
150
- return original_chatbot(input_text, enable_voice)
151
-
152
- def original_chatbot(input_text, enable_voice):
153
- load_training_data()
154
- matching_records = search_partial_matches(input_text)
155
-
156
- total_money = 0
157
- filtered_records = {}
158
-
159
- for key, records in matching_records.items():
160
- filtered_records[key] = [info for info in records if "شيكل" in info.get("تقرير نهائي", "")]
161
-
162
- res_list = []
163
-
164
- if filtered_records:
165
- responses = []
166
-
167
- for key, records in filtered_records.items():
168
- if key == "رقم المركبة":
169
- company_name = records[0].get("اسم الشركه", "")
170
- res_list.append(f"اسم الشركة هو: {company_name}")
171
-
172
- for info in records:
173
- response = "\n".join([f"{key}: {value}" for key, value in info.items()])
174
- responses.append(response)
175
- report = info.get("تقرير نهائي", "")
176
- if "شغل" in report:
177
- money_values = re.findall(r'شغل\s*(\d+)\s*شيكل', report)
178
- else:
179
- money_values = re.findall(r'(\d+)\s*شيكل', report)
180
- money_values = [int(value) for value in money_values]
181
- total_money += sum(money_values)
182
-
183
- num_records_found = f"Number of records found: {len(responses)}"
184
- total_money_str = f"Total Money: {total_money} شيكل"
185
- combined_output = f"{num_records_found} - {total_money_str}"
186
- response = "\n\n---\n\n".join(responses)
187
- res_list.append(f"مجموع الدخل اليومي في هذا اليوم هو: {total_money}")
188
- else:
189
- combined_output = "No matching entries found in the data."
190
- response = ""
191
-
192
- weekly_total = calculate_weekly_total(input_text)
193
- res_list.append(f"مجموع الدخل الأسبوعي هو: {weekly_total}")
194
-
195
- weekly_cash_total = calculate_weekly_cash_total(input_text)
196
- res_list.append(f"مجموع الكاش المقبوض في هذا الاسبوع هو: {weekly_cash_total}")
197
-
198
- audio_file = None
199
- if enable_voice:
200
- audio_file = text_to_speech("\n".join(res_list))
201
-
202
- return (combined_output, response, f"Weekly Total: {weekly_total} - Weekly Cash Total: {weekly_cash_total}", audio_file)
203
-
204
- iface = gr.Interface(
205
- fn=chatbot,
206
- inputs=[
207
- gr.Textbox(lines=2, placeholder="Enter Date or Company Name or Plate Number..."),
208
- gr.Textbox(lines=1, placeholder="بحث من تاريخ (dd.mm.yyyy)", label="بحث من تاريخ"),
209
- gr.Textbox(lines=1, placeholder="الى تاريخ (dd.mm.yyyy)", label="الى تاريخ"),
210
- gr.Checkbox(label="تفعيل الصوت") # Checkbox for enabling voice output
211
- ],
212
- outputs=[
213
- gr.Textbox(label="مجموع الدخل اليومي"),
214
- gr.Textbox(label="عرض التقارير"),
215
- gr.Textbox(label="مجموع الدخل الاسبوعي"),
216
- gr.Audio(label="Play Voice") # Audio output for playing the voice
217
- ],
218
- live=False,
219
- title="شركه ابناء عرفات",
220
- description="بحث حسب اسم الشركه - التاريخ - نمره الشاحنه"
221
- )
222
-
223
- if __name__ == "__main__":
224
- iface.launch(share=True)
 
1
+ import threading
2
+ import time
3
+ import openai
4
+ import gradio as gr
5
+ import csv
6
+ import re
7
+ import os
8
+ from datetime import datetime, timedelta
9
+ from gtts import gTTS
10
+ from queue import Queue
11
+
12
+ # Set your OpenAI API key
13
+ openai.api_key = 'YOUR_API_KEY'
14
+
15
+ # Global TTS queue
16
+ tts_queue = Queue()
17
+
18
+ # Load data from the CSV file when the application starts
19
+ data = None
20
+
21
+ def load_training_data():
22
+ global data
23
+ if data is None:
24
+ data = {}
25
+ with open("docs/your_data.csv", "r", encoding="utf-8-sig") as csvfile:
26
+ reader = csv.DictReader(csvfile)
27
+ for row in reader:
28
+ plate_number = row.get("رقم المركبة", "").strip()
29
+ company_name = row.get("اسم الشركه", "").strip()
30
+ date = row.get("تاريخ الدخول", "").strip()
31
+
32
+ if plate_number not in data:
33
+ data[plate_number] = []
34
+ data[plate_number].append(row)
35
+
36
+ if company_name not in data:
37
+ data[company_name] = []
38
+ data[company_name].append(row)
39
+
40
+ if date not in data:
41
+ data[date] = []
42
+ data[date].append(row)
43
+
44
+ def parse_date(date_str):
45
+ return datetime.strptime(date_str, "%d.%m.%Y")
46
+
47
+ def get_week_range(date_str):
48
+ current_date = parse_date(date_str)
49
+ days_to_subtract = (current_date.weekday() + 2) % 7
50
+ start_of_week = current_date - timedelta(days=days_to_subtract)
51
+ end_of_week = start_of_week + timedelta(days=6)
52
+ return start_of_week, end_of_week
53
+
54
+ def text_to_speech(text):
55
+ try:
56
+ speech = gTTS(text=text, lang='ar', slow=False)
57
+ filename = f"text_to_speech_{int(time.time())}.mp3"
58
+ filepath = os.path.join("static", filename)
59
+ speech.save(filepath)
60
+ return filepath
61
+ except Exception as e:
62
+ print("Exception:", str(e))
63
+ return None
64
+
65
+ def calculate_weekly_total(date_str):
66
+ load_training_data()
67
+ try:
68
+ input_date = parse_date(date_str)
69
+ except ValueError:
70
+ return "Invalid date format. Please enter a date in the format dd.mm.yyyy."
71
+ start_of_week, end_of_week = get_week_range(date_str)
72
+ weekly_total = 0
73
+ for date_key in data.keys():
74
+ try:
75
+ record_date = parse_date(date_key)
76
+ if start_of_week <= record_date <= end_of_week:
77
+ for record in data[date_key]:
78
+ report = record.get("تقرير نهائي", "")
79
+ if "شغل" in report:
80
+ money_values = re.findall(r'شغل\s*(\d+)\s*شيكل', report)
81
+ else:
82
+ money_values = re.findall(r'(\d+)\s*شيكل', report)
83
+ money_values = [int(value) for value in money_values]
84
+ weekly_total += sum(money_values)
85
+ except ValueError:
86
+ continue
87
+ return weekly_total
88
+
89
+ def calculate_weekly_cash_total(date_str):
90
+ load_training_data()
91
+ try:
92
+ input_date = parse_date(date_str)
93
+ except ValueError:
94
+ return "Invalid date format. Please enter a date in the format dd.mm.yyyy."
95
+ start_of_week, end_of_week = get_week_range(date_str)
96
+ weekly_cash_total = 0
97
+ for date_key in data.keys():
98
+ try:
99
+ record_date = parse_date(date_key)
100
+ if start_of_week <= record_date <= end_of_week:
101
+ for record in data[date_key]:
102
+ plate_number = record.get("رقم المركبة", "")
103
+ if "كاش" in plate_number:
104
+ report = record.get("تقرير نهائي", "")
105
+ money_values = re.findall(r'(\d+)\s*شيكل', report)
106
+ money_values = [int(value) for value in money_values]
107
+ weekly_cash_total += sum(money_values)
108
+ except ValueError:
109
+ continue
110
+ return weekly_cash_total
111
+
112
+ def search_partial_matches(input_text):
113
+ load_training_data()
114
+ input_text = input_text.strip()
115
+ matching_records = {}
116
+ for key in data.keys():
117
+ if input_text in key:
118
+ matching_records[key] = data[key]
119
+ return matching_records
120
+
121
+ def calculate_total_for_period(start_date_str, end_date_str):
122
+ load_training_data()
123
+ try:
124
+ start_date = parse_date(start_date_str)
125
+ end_date = parse_date(end_date_str)
126
+ except ValueError:
127
+ return "Invalid date format. Please enter dates in the format dd.mm.yyyy."
128
+ total_amount = 0
129
+ for date_key in data.keys():
130
+ try:
131
+ record_date = parse_date(date_key)
132
+ if start_date <= record_date <= end_date:
133
+ for record in data[date_key]:
134
+ report = record.get("تقرير نهائي", "")
135
+ if "شغل" in report:
136
+ money_values = re.findall(r'شغل\s*(\d+)\s*شيكل', report)
137
+ else:
138
+ money_values = re.findall(r'(\d+)\s*شيكل', report)
139
+ money_values = [int(value) for value in money_values]
140
+ total_amount += sum(money_values)
141
+ except ValueError:
142
+ continue
143
+ return total_amount
144
+
145
+ def chatbot(input_text, start_date_str="", end_date_str="", enable_voice=False):
146
+ if start_date_str and end_date_str:
147
+ total_for_period = calculate_total_for_period(start_date_str, end_date_str)
148
+ return (f"Total amount from {start_date_str} to {end_date_str}: {total_for_period} شيكل", "", "", None)
149
+ else:
150
+ return original_chatbot(input_text, enable_voice)
151
+
152
+ def original_chatbot(input_text, enable_voice):
153
+ load_training_data()
154
+ matching_records = search_partial_matches(input_text)
155
+
156
+ total_money = 0
157
+ filtered_records = {}
158
+
159
+ for key, records in matching_records.items():
160
+ filtered_records[key] = [info for info in records if "شيكل" in info.get("تقرير نهائي", "")]
161
+
162
+ res_list = []
163
+
164
+ if filtered_records:
165
+ responses = []
166
+
167
+ for key, records in filtered_records.items():
168
+ if key == "رقم المركبة":
169
+ company_name = records[0].get("اسم الشركه", "")
170
+ res_list.append(f"اسم الشركة هو: {company_name}")
171
+
172
+ for info in records:
173
+ response = "\n".join([f"{key}: {value}" for key, value in info.items()])
174
+ responses.append(response)
175
+ report = info.get("تقرير نهائي", "")
176
+ if "شغل" in report:
177
+ money_values = re.findall(r'شغل\s*(\d+)\s*شيكل', report)
178
+ else:
179
+ money_values = re.findall(r'(\d+)\s*شيكل', report)
180
+ money_values = [int(value) for value in money_values]
181
+ total_money += sum(money_values)
182
+
183
+ num_records_found = f"Number of records found: {len(responses)}"
184
+ total_money_str = f"Total Money: {total_money} شيكل"
185
+ combined_output = f"{num_records_found} - {total_money_str}"
186
+ response = "\n\n---\n\n".join(responses)
187
+ res_list.append(f"مجموع الدخل اليومي في هذا اليوم هو: {total_money}")
188
+ else:
189
+ combined_output = "No matching entries found in the data."
190
+ response = ""
191
+
192
+ weekly_total = calculate_weekly_total(input_text)
193
+ res_list.append(f"مجموع الدخل الأسبوعي هو: {weekly_total}")
194
+
195
+ weekly_cash_total = calculate_weekly_cash_total(input_text)
196
+ res_list.append(f"مجموع الكاش المقبوض في هذا الاسبوع هو: {weekly_cash_total}")
197
+
198
+ audio_file = None
199
+ if enable_voice:
200
+ audio_file = text_to_speech("\n".join(res_list))
201
+
202
+ return (combined_output, response, f"Weekly Total: {weekly_total} - Weekly Cash Total: {weekly_cash_total}", audio_file)
203
+
204
+ iface = gr.Interface(
205
+ fn=chatbot,
206
+ inputs=[
207
+ gr.Textbox(lines=2, placeholder="Enter Date or Company Name or Plate Number..."),
208
+ gr.Textbox(lines=1, placeholder="بحث من تاريخ (dd.mm.yyyy)", label="بحث من تاريخ"),
209
+ gr.Textbox(lines=1, placeholder="الى تاريخ (dd.mm.yyyy)", label="الى تاريخ"),
210
+ gr.Checkbox(label="تفعيل الصوت") # Checkbox for enabling voice output
211
+ ],
212
+ outputs=[
213
+ gr.Textbox(label="مجموع الدخل اليومي"),
214
+ gr.Textbox(label="عرض التقارير"),
215
+ gr.Textbox(label="مجموع الدخل الاسبوعي"),
216
+ gr.Audio(label="Play Voice") # Audio output for playing the voice
217
+ ],
218
+ live=False,
219
+ title="شركه ابناء عرفات",
220
+ description="بحث حسب اسم الشركه - التاريخ - نمره الشاحنه"
221
+ )
222
+
223
+ if __name__ == "__main__":
224
+ iface.launch(share=True)
app.log CHANGED
The diff for this file is too large to render. See raw diff
 
docs/your_data.csv CHANGED
The diff for this file is too large to render. See raw diff
 
flagged/log.csv CHANGED
@@ -1,4 +1,4 @@
1
- input_text,output,flag,username,timestamp
2
  29.10,"رقم المركبة:
3
  نوع المركبه:
4
  تاريخ الدخول: 29.10.2023
@@ -333,4 +333,4 @@ input_text,output,flag,username,timestamp
333
  اسم الميكانيكي:
334
  ملاحظات:
335
  ملاحظات 2:
336
- تقرير نهائي: ثمن شمزه محاليق - - - - - - - - - - - - 150 شيكل ",,,2023-10-30 17:16:38.805830
 
1
+ input_text,output,flag,username,timestamp
2
  29.10,"رقم المركبة:
3
  نوع المركبه:
4
  تاريخ الدخول: 29.10.2023
 
333
  اسم الميكانيكي:
334
  ملاحظات:
335
  ملاحظات 2:
336
+ تقرير نهائي: ثمن شمزه محاليق - - - - - - - - - - - - 150 شيكل ",,,2023-10-30 17:16:38.805830
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
- gradio==4.4.1
2
- gTTS==2.4.0
3
- pygame==2.5.2
4
  openai==0.28.1
 
1
+ gradio==4.4.1
2
+ gTTS==2.4.0
3
+ pygame==2.5.2
4
  openai==0.28.1
run.bat CHANGED
@@ -1,2 +1,2 @@
1
- @echo off
2
- cmd /k python 5.py
 
1
+ @echo off
2
+ cmd /k python 5.py