neuralworm commited on
Commit
084e807
·
1 Parent(s): 337ca61

filtering, upgrade

Browse files
Files changed (2) hide show
  1. app.py +77 -37
  2. requirements.txt +5 -5
app.py CHANGED
@@ -36,7 +36,6 @@ def date_to_words(date_string):
36
  date_obj = datetime.strptime(date_string, "%Y-%m-%d")
37
  return format_date(date_obj, inf_engine)
38
 
39
-
40
  def month_year_to_words(date_string):
41
  """Converts a month and year in YYYY-MM format to English words."""
42
  inf_engine = inflect.engine()
@@ -44,9 +43,10 @@ def month_year_to_words(date_string):
44
  return format_date(date_obj, inf_engine)
45
 
46
  def format_date(date_obj, inf_engine):
 
47
  year = date_obj.year
48
  if 1100 <= year <= 1999:
49
- year_words = f"{inf_engine.number_to_words(year // 100, andword='') } hundred"
50
  if year % 100 != 0:
51
  year_words += f" {inf_engine.number_to_words(year % 100, andword='')}"
52
  else:
@@ -54,14 +54,11 @@ def format_date(date_obj, inf_engine):
54
  year_formatted = year_words.replace(',', '')
55
 
56
  month = date_obj.strftime("%B")
57
-
58
- try: # Try getting the day, if available
59
- day = date_obj.day
60
- day_ordinal = number_to_ordinal_word(day)
61
- return f"{day_ordinal} {month} {year_formatted}" # Return with day
62
- except:
63
- return f"{month} {year_formatted}" # Return without day
64
 
 
 
 
 
65
 
66
  def format_year_to_words(year):
67
  """Formats a year as English words."""
@@ -75,17 +72,17 @@ def format_year_to_words(year):
75
  return year_words.replace(',', '')
76
 
77
  def perform_gematria_calculation_for_date_range(start_date, end_date):
78
- """Performs gematria calculation for a date range and groups by sum."""
79
  logger.debug(f"Start Date: {start_date}, End Date: {end_date}")
80
  results = {}
81
  delta = timedelta(days=1)
82
  current_date = start_date
83
 
84
  processed_months = set() # To track processed month-year combinations
85
- processed_years = set() # To track processed years
86
 
87
  while current_date <= end_date:
88
- # Full date calculation
89
  date_string = current_date.strftime("%Y-%m-%d")
90
  date_words = date_to_words(date_string)
91
  gematria_sum = calculate_gematria_sum(date_words)
@@ -94,7 +91,7 @@ def perform_gematria_calculation_for_date_range(start_date, end_date):
94
  results[gematria_sum] = []
95
  results[gematria_sum].append({"date": date_string, "date_words": date_words})
96
 
97
- # Month+Year calculation (processed once per month)
98
  month_year_key = current_date.strftime("%Y-%m")
99
  if month_year_key not in processed_months:
100
  processed_months.add(month_year_key)
@@ -108,7 +105,7 @@ def perform_gematria_calculation_for_date_range(start_date, end_date):
108
  "date_words": month_year_words
109
  })
110
 
111
- # Year-only calculation (processed once per year)
112
  year_key = str(current_date.year)
113
  if year_key not in processed_years:
114
  processed_years.add(year_key)
@@ -126,40 +123,56 @@ def perform_gematria_calculation_for_date_range(start_date, end_date):
126
 
127
  return results
128
 
129
-
130
  # --- Event Handlers ---
131
- def perform_calculation(start_date, end_date, include_words):
132
- """Performs the calculation and generates the JSON output."""
133
- logger.debug(f"perform_calculation called with: start_date={start_date}, end_date={end_date}, include_words={include_words}")
134
- results = perform_gematria_calculation_for_date_range(start_date, end_date)
135
- json_result = generate_json_output(results, start_date, end_date, include_words)
136
- return json_result
137
-
138
-
139
- def generate_json_output(results, start_date, end_date, include_words):
140
- """Generates the JSON output with the date range and results."""
141
- result = {
142
  "DateRange": {
143
  "StartDate": start_date.strftime("%Y-%m-%d"),
144
  "EndDate": end_date.strftime("%Y-%m-%d")
145
  },
146
  "Results": []
147
  }
 
148
  for gematria_sum, entries in results.items():
 
 
 
 
149
  group = {
150
  "GematriaSum": gematria_sum,
151
  "Entries": []
152
  }
153
  for entry in entries:
154
  entry_data = {"date": entry["date"]}
155
- if include_words: # Conditionally include `date_words`
156
  entry_data["date_words"] = entry["date_words"]
157
  group["Entries"].append(entry_data)
158
- result["Results"].append(group)
159
 
160
- # Ensure JSON validity
161
- return json.dumps(result, indent=4, ensure_ascii=False)
 
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  # --- Main Gradio App ---
165
  with gr.Blocks() as app:
@@ -167,25 +180,52 @@ with gr.Blocks() as app:
167
  start_date = Calendar(type="datetime", label="Start Date")
168
  end_date = Calendar(type="datetime", label="End Date")
169
 
170
- include_date_words = gr.Checkbox(value=True, label="Include Date-Words in JSON")
 
 
 
 
 
 
 
 
 
171
 
172
  calculate_btn = gr.Button("Calculate Gematria for Date Range")
173
- json_output = gr.Textbox(label="JSON Output")
174
  download_btn = gr.Button("Download JSON")
175
  json_file = gr.File(label="Downloaded JSON")
176
 
177
- # --- Event Triggers ---
 
 
 
 
 
 
 
 
 
 
 
178
  calculate_btn.click(
179
- perform_calculation,
180
- inputs=[start_date, end_date, include_date_words],
181
  outputs=[json_output],
182
  api_name="calculate_gematria"
183
  )
184
 
185
  download_btn.click(
186
- lambda json_data, start_date, end_date: download_json(json_data, start_date, end_date),
187
  inputs=[json_output, start_date, end_date],
188
- outputs=[json_file],
 
 
 
 
 
 
 
189
  )
190
 
191
  if __name__ == "__main__":
 
36
  date_obj = datetime.strptime(date_string, "%Y-%m-%d")
37
  return format_date(date_obj, inf_engine)
38
 
 
39
  def month_year_to_words(date_string):
40
  """Converts a month and year in YYYY-MM format to English words."""
41
  inf_engine = inflect.engine()
 
43
  return format_date(date_obj, inf_engine)
44
 
45
  def format_date(date_obj, inf_engine):
46
+ """Formats day-month-year into English words with ordinal day."""
47
  year = date_obj.year
48
  if 1100 <= year <= 1999:
49
+ year_words = f"{inf_engine.number_to_words(year // 100, andword='')} hundred"
50
  if year % 100 != 0:
51
  year_words += f" {inf_engine.number_to_words(year % 100, andword='')}"
52
  else:
 
54
  year_formatted = year_words.replace(',', '')
55
 
56
  month = date_obj.strftime("%B")
 
 
 
 
 
 
 
57
 
58
+ # Tag auslesen und in Ordinalform umwandeln
59
+ day = date_obj.day
60
+ day_ordinal = number_to_ordinal_word(day)
61
+ return f"{day_ordinal} {month} {year_formatted}"
62
 
63
  def format_year_to_words(year):
64
  """Formats a year as English words."""
 
72
  return year_words.replace(',', '')
73
 
74
  def perform_gematria_calculation_for_date_range(start_date, end_date):
75
+ """Performs gematria calculation for each day in a date range and groups by sum."""
76
  logger.debug(f"Start Date: {start_date}, End Date: {end_date}")
77
  results = {}
78
  delta = timedelta(days=1)
79
  current_date = start_date
80
 
81
  processed_months = set() # To track processed month-year combinations
82
+ processed_years = set() # To track processed years
83
 
84
  while current_date <= end_date:
85
+ # 1) Full date calculation
86
  date_string = current_date.strftime("%Y-%m-%d")
87
  date_words = date_to_words(date_string)
88
  gematria_sum = calculate_gematria_sum(date_words)
 
91
  results[gematria_sum] = []
92
  results[gematria_sum].append({"date": date_string, "date_words": date_words})
93
 
94
+ # 2) Month+Year calculation (only once per unique month-year)
95
  month_year_key = current_date.strftime("%Y-%m")
96
  if month_year_key not in processed_months:
97
  processed_months.add(month_year_key)
 
105
  "date_words": month_year_words
106
  })
107
 
108
+ # 3) Year-only calculation (only once per unique year)
109
  year_key = str(current_date.year)
110
  if year_key not in processed_years:
111
  processed_years.add(year_key)
 
123
 
124
  return results
125
 
 
126
  # --- Event Handlers ---
127
+ def generate_json_output(results, start_date, end_date, include_words, min_results):
128
+ """
129
+ Erzeugt ein Dictionary (später für gr.JSON) mit Filterung nach Mindestanzahl,
130
+ wenn min_results nicht None ist.
131
+ """
132
+ output = {
 
 
 
 
 
133
  "DateRange": {
134
  "StartDate": start_date.strftime("%Y-%m-%d"),
135
  "EndDate": end_date.strftime("%Y-%m-%d")
136
  },
137
  "Results": []
138
  }
139
+
140
  for gematria_sum, entries in results.items():
141
+ # Falls eine Mindestanzahl gefordert ist, filtern
142
+ if min_results is not None and len(entries) < min_results:
143
+ continue
144
+
145
  group = {
146
  "GematriaSum": gematria_sum,
147
  "Entries": []
148
  }
149
  for entry in entries:
150
  entry_data = {"date": entry["date"]}
151
+ if include_words:
152
  entry_data["date_words"] = entry["date_words"]
153
  group["Entries"].append(entry_data)
 
154
 
155
+ output["Results"].append(group)
156
+
157
+ return output # <-- Wichtig: Als Dictionary zurückgeben
158
 
159
+ def perform_calculation(start_date, end_date, include_words, min_results):
160
+ """
161
+ Führt die Gematria-Berechnung durch und gibt ein Dictionary zurück,
162
+ das direkt an gr.JSON übergeben werden kann.
163
+ """
164
+ results = perform_gematria_calculation_for_date_range(start_date, end_date)
165
+ return generate_json_output(results, start_date, end_date, include_words, min_results)
166
+
167
+ def download_json(json_data, start_date, end_date):
168
+ """
169
+ Nimmt das Dictionary aus json_data (von gr.JSON), verwandelt es in einen JSON-String
170
+ und gibt es zum Downloaden als .json zurück.
171
+ """
172
+ filename = f"gematria_{start_date.strftime('%Y%m%d')}_{end_date.strftime('%Y%m%d')}.json"
173
+ # Hier wandeln wir das Dictionary in einen String um
174
+ json_string = json.dumps(json_data, indent=4, ensure_ascii=False)
175
+ return gr.File.update(value=json_string, filename=filename)
176
 
177
  # --- Main Gradio App ---
178
  with gr.Blocks() as app:
 
180
  start_date = Calendar(type="datetime", label="Start Date")
181
  end_date = Calendar(type="datetime", label="End Date")
182
 
183
+ with gr.Row():
184
+ include_date_words = gr.Checkbox(
185
+ value=True, label="Include Date-Words in JSON"
186
+ )
187
+ filter_results = gr.Checkbox(
188
+ value=False, label="Filter to sums with at least"
189
+ )
190
+ min_results_input = gr.Number(
191
+ value=2, label="results", interactive=True, precision=0
192
+ )
193
 
194
  calculate_btn = gr.Button("Calculate Gematria for Date Range")
195
+ json_output = gr.JSON(label="JSON Output") # Präsentation als JSON
196
  download_btn = gr.Button("Download JSON")
197
  json_file = gr.File(label="Downloaded JSON")
198
 
199
+ # Damit wir den Wert von filter_results berücksichtigen können:
200
+ def handle_calculate(start_val, end_val, include_val, filter_val, min_val):
201
+ if not filter_val: # Checkbox nicht gesetzt
202
+ # => Kein Filtern, also min_results=None
203
+ return perform_calculation(start_val, end_val, include_val, None)
204
+ else:
205
+ # => Filter aktiviert, also min_results = min_val
206
+ # min_val kann float sein; auf int casten, falls gewünscht
207
+ return perform_calculation(start_val, end_val, include_val, int(min_val))
208
+
209
+ # Button-Klick: wir rufen handle_calculate auf,
210
+ # das ggf. min_results auf None setzt oder den Wert übernimmt.
211
  calculate_btn.click(
212
+ handle_calculate,
213
+ inputs=[start_date, end_date, include_date_words, filter_results, min_results_input],
214
  outputs=[json_output],
215
  api_name="calculate_gematria"
216
  )
217
 
218
  download_btn.click(
219
+ download_json,
220
  inputs=[json_output, start_date, end_date],
221
+ outputs=[json_file]
222
+ )
223
+
224
+ # Aktiviert/Deaktiviert die Eingabe für min_results
225
+ filter_results.change(
226
+ lambda checked: gr.update(interactive=checked),
227
+ inputs=filter_results,
228
+ outputs=min_results_input
229
  )
230
 
231
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- fastapi==0.112.3
2
- gradio==4.31.0
3
- deep_translator==1.11.4
4
- gradio_calendar==0.0.4
5
- inflect==7.2.1
 
1
+ #fastapi==0.112.3
2
+ gradio==5.5.0
3
+ deep_translator
4
+ gradio_calendar
5
+ inflect