rmayormartins commited on
Commit
e268a60
1 Parent(s): 2894dda

Atualização

Browse files
Files changed (2) hide show
  1. README.md +5 -1
  2. app.py +30 -31
README.md CHANGED
@@ -12,4 +12,8 @@ license: ecl-2.0
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
 
15
- Desenvolvido por Ramon Mayor Martins rmayormartins@gmail.com twitter @rmayormartins
 
 
 
 
 
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
 
15
+ Desenvolvido por Ramon Mayor Martins (2023)
16
+ mail rmayormartins@gmail.com
17
+ hp https://rmayormartins.github.io/
18
+ twitter @rmayormartins
19
+ github https://github.com/rmayormartins
app.py CHANGED
@@ -9,13 +9,13 @@ import json
9
  import glob
10
  from io import BytesIO
11
 
12
- # Padrões de IA
13
  ai_patterns = [
14
  "PIC*", "PersonalImageClassifier*", "Look*", "LookExtension*", "ChatBot", "ImageBot", "TMIC","TeachableMachine*",
15
  "TeachableMachineImageClassifier*", "SpeechRecognizer*", "FaceExtension*","Pose*","Posenet","PosenetExtension", "Eliza*", "Alexa*"
16
  ]
17
 
18
- # Padrões para cada categoria
19
  drawing_and_animation_patterns = ["Ball", "Canvas", "ImageSprite"]
20
  maps_patterns = ["Map", "Marker", "Circle", "FeatureCollection", "LineString", "Navigation","Polygon", "Retangle" ]
21
  sensors_patterns = ["AccelerometerSensor", "BarcodeScanner", "Barometer", "Clock", "GyroscopeSensor", "Hygrometer", "LightSensor", "LocationSensor", "MagneticFieldSensor", "NearField","OrientationSensor", "ProximitySensor","Thermometer", "Pedometer"]
@@ -56,7 +56,7 @@ def extract_extensions_from_aia(file_path: str):
56
  return extensions
57
 
58
  def count_events_in_bky_file(bky_content):
59
- # Counting the number of occurrences of the "component_event" blocks
60
  return bky_content.count('<block type="component_event"')
61
 
62
  def extract_app_name_from_scm_files(temp_dir):
@@ -65,10 +65,10 @@ def extract_app_name_from_scm_files(temp_dir):
65
  with open(scm_file, 'r', encoding='utf-8', errors='ignore') as file:
66
  content = file.read()
67
 
68
- # Tenta várias expressões regulares para encontrar o nome do aplicativo
69
  regex_patterns = [
70
  r'"AppName"\s*:\s*"([^"]+)"',
71
- r'"AppName"\s*:\s*\'([^\']+)\'' # Exemplo de outra possível expressão regular
72
  ]
73
 
74
  for pattern in regex_patterns:
@@ -76,33 +76,33 @@ def extract_app_name_from_scm_files(temp_dir):
76
  if app_name_match:
77
  return app_name_match.group(1)
78
 
79
- # Log de erros ou avisos
80
  print(f"Aviso: Nome do aplicativo não encontrado no diretório {temp_dir}")
81
  return "N/A"
82
 
83
  def extract_project_info_from_properties(file_path):
84
- # Initialize variables
85
  timestamp = "N/A"
86
  app_name = "N/A"
87
  app_version = "N/A"
88
  authURL = "ai2.appinventor.mit.edu"
89
 
90
- # Create a temporary directory
91
  with tempfile.TemporaryDirectory() as temp_dir:
92
  with ZipFile(file_path, 'r') as zip_ref:
93
  zip_ref.extractall(temp_dir)
94
- # Define the path to the 'project.properties' file
95
  project_properties_file_path = 'youngandroidproject/project.properties'
96
 
97
- # Check if the file exists in the .aia file
98
  if project_properties_file_path in zip_ref.namelist():
99
  with zip_ref.open(project_properties_file_path) as file:
100
  project_properties_lines = file.read().decode('utf-8').splitlines()
101
 
102
- # Extracting timestamp
103
  timestamp = project_properties_lines[1] if len(project_properties_lines) > 1 else "N/A"
104
 
105
- # Extracting app name and version using regular expressions
106
  for line in project_properties_lines:
107
  app_name_match = re.match(r'aname=(.*)', line)
108
  if app_name_match:
@@ -112,7 +112,7 @@ def extract_project_info_from_properties(file_path):
112
  if app_version_match:
113
  app_version = app_version_match.group(1)
114
 
115
- # Complementary method for extracting the app name from .scm files
116
  if app_name == "N/A":
117
  print("O campo App Name não foi encontrado em project.properties. Tentando encontrar em arquivos .scm...")
118
  app_name = extract_app_name_from_scm_files(temp_dir)
@@ -153,7 +153,7 @@ def extract_media_files(file_path: str):
153
  return media_files
154
 
155
  def list_components_in_aia_file(file_path):
156
- # Inicialize results_df aqui
157
  results_df = pd.DataFrame(columns=[
158
  'aia_file', 'project_info', 'components', 'IA components', 'screens', 'operators',
159
  'variables', 'events', 'extensions', 'Media',
@@ -162,17 +162,17 @@ def list_components_in_aia_file(file_path):
162
 
163
  pd.set_option('display.max_colwidth', None)
164
  file_name = os.path.basename(file_path)
165
- # ... restante do código ...
166
 
167
  components_list = []
168
  number_of_screens = 0
169
  operators_count = 0
170
  variables_count = 0
171
- events_count = 0 # Adicione esta variável para contar os eventos
172
- # Extrair arquivos de mídia
173
  media_files = extract_media_files(file_path)
174
  media_summary = ', '.join(media_files)
175
- # Extracting project information
176
  project_info = extract_project_info_from_properties(file_path)
177
  project_info_str = f"Timestamp: {project_info['timestamp']}, App Name: {project_info['app_name']}, Version: {project_info['app_version']}, AuthURL: {project_info['authURL']}"
178
 
@@ -181,7 +181,7 @@ def list_components_in_aia_file(file_path):
181
  with ZipFile(file_path, 'r') as zip_ref:
182
  zip_ref.extractall(temp_dir)
183
  scm_files = glob.glob(temp_dir + '/src/appinventor/*/*/*.scm')
184
- bky_files = glob.glob(temp_dir + '/src/appinventor/*/*/*.bky') # Esta linha define bky_files
185
 
186
  number_of_screens = len(scm_files)
187
  for scm_file in scm_files:
@@ -192,7 +192,7 @@ def list_components_in_aia_file(file_path):
192
  operators_count += len(re.findall(r'[+\-*/<>!=&|]', content))
193
  variables_count += len(re.findall(r'"\$Name":"(.*?)"', content))
194
 
195
- # Extração dos componentes de cada categoria
196
  drawing_and_animation_summary = ', '.join(extract_category_components(components_list, drawing_and_animation_patterns))
197
  maps_summary = ', '.join(extract_category_components(components_list, maps_patterns))
198
  sensors_summary = ', '.join(extract_category_components(components_list, sensors_patterns))
@@ -201,8 +201,8 @@ def list_components_in_aia_file(file_path):
201
  connectivity_summary = ', '.join(extract_category_components(components_list, connectivity_patterns))
202
 
203
 
204
- # Adicione este bloco para contar os eventos nos arquivos .bky
205
- # Extracting extensions from .bky files
206
  extensions_list = []
207
  extensions_list = extract_extensions_from_aia(file_path)
208
 
@@ -210,10 +210,10 @@ def list_components_in_aia_file(file_path):
210
  with open(bky_file, 'r', encoding='utf-8', errors='ignore') as file:
211
  bky_content = file.read()
212
  events_count += count_events_in_bky_file(bky_content)
213
- #extensions_list.extend(extract_extensions_from_bky(bky_content))
214
 
215
 
216
- # Creating a summary of the extracted extensions
217
  extensions_summary = ', '.join(list(set(extensions_list)))
218
 
219
  components_count = collections.Counter(components_list)
@@ -238,13 +238,12 @@ def list_components_in_aia_file(file_path):
238
  'Connectivity': connectivity_summary
239
  }])
240
 
241
- # Concatene new_row ao results_df
242
  results_df = pd.concat([results_df, new_row], ignore_index=True)
243
  return results_df
244
  #
245
 
246
- # Define a altura máxima para o output e habilite a rolagem
247
- # Adicione a variável de estilo CSS ao início do seu código, fora da função analyze_aia
248
  output_style = """
249
  <style>
250
  .output-container {
@@ -264,10 +263,10 @@ output_style = """
264
  </style>
265
  """
266
 
267
- # Esta será a função que a interface do Gradio irá chamar
268
  def analyze_aia(uploaded_file):
269
  try:
270
- # Obtendo o caminho do arquivo a partir do objeto uploaded_file
271
  file_path = uploaded_file.name if hasattr(uploaded_file, 'name') else None
272
 
273
  if file_path and os.path.exists(file_path):
@@ -275,7 +274,7 @@ def analyze_aia(uploaded_file):
275
  with tempfile.TemporaryDirectory() as temp_dir:
276
  zip_ref.extractall(temp_dir)
277
  results_df = list_components_in_aia_file(file_path)
278
- # Inclua o estilo CSS na resposta HTML
279
  html_result = results_df.to_html(escape=False, classes="output-html")
280
  return output_style + f'<div class="output-container">{html_result}</div>'
281
 
@@ -295,7 +294,7 @@ iface = gr.Interface(
295
  outputs=gr.HTML(),
296
  title="AIA-Scope",
297
  description="Upload an .aia file to analyze its components.",
298
- live=False # Isso garante que o botão Submit seja necessário
299
  )
300
 
301
  if __name__ == "__main__":
 
9
  import glob
10
  from io import BytesIO
11
 
12
+
13
  ai_patterns = [
14
  "PIC*", "PersonalImageClassifier*", "Look*", "LookExtension*", "ChatBot", "ImageBot", "TMIC","TeachableMachine*",
15
  "TeachableMachineImageClassifier*", "SpeechRecognizer*", "FaceExtension*","Pose*","Posenet","PosenetExtension", "Eliza*", "Alexa*"
16
  ]
17
 
18
+
19
  drawing_and_animation_patterns = ["Ball", "Canvas", "ImageSprite"]
20
  maps_patterns = ["Map", "Marker", "Circle", "FeatureCollection", "LineString", "Navigation","Polygon", "Retangle" ]
21
  sensors_patterns = ["AccelerometerSensor", "BarcodeScanner", "Barometer", "Clock", "GyroscopeSensor", "Hygrometer", "LightSensor", "LocationSensor", "MagneticFieldSensor", "NearField","OrientationSensor", "ProximitySensor","Thermometer", "Pedometer"]
 
56
  return extensions
57
 
58
  def count_events_in_bky_file(bky_content):
59
+
60
  return bky_content.count('<block type="component_event"')
61
 
62
  def extract_app_name_from_scm_files(temp_dir):
 
65
  with open(scm_file, 'r', encoding='utf-8', errors='ignore') as file:
66
  content = file.read()
67
 
68
+
69
  regex_patterns = [
70
  r'"AppName"\s*:\s*"([^"]+)"',
71
+ r'"AppName"\s*:\s*\'([^\']+)\''
72
  ]
73
 
74
  for pattern in regex_patterns:
 
76
  if app_name_match:
77
  return app_name_match.group(1)
78
 
79
+
80
  print(f"Aviso: Nome do aplicativo não encontrado no diretório {temp_dir}")
81
  return "N/A"
82
 
83
  def extract_project_info_from_properties(file_path):
84
+
85
  timestamp = "N/A"
86
  app_name = "N/A"
87
  app_version = "N/A"
88
  authURL = "ai2.appinventor.mit.edu"
89
 
90
+
91
  with tempfile.TemporaryDirectory() as temp_dir:
92
  with ZipFile(file_path, 'r') as zip_ref:
93
  zip_ref.extractall(temp_dir)
94
+
95
  project_properties_file_path = 'youngandroidproject/project.properties'
96
 
97
+
98
  if project_properties_file_path in zip_ref.namelist():
99
  with zip_ref.open(project_properties_file_path) as file:
100
  project_properties_lines = file.read().decode('utf-8').splitlines()
101
 
102
+
103
  timestamp = project_properties_lines[1] if len(project_properties_lines) > 1 else "N/A"
104
 
105
+
106
  for line in project_properties_lines:
107
  app_name_match = re.match(r'aname=(.*)', line)
108
  if app_name_match:
 
112
  if app_version_match:
113
  app_version = app_version_match.group(1)
114
 
115
+
116
  if app_name == "N/A":
117
  print("O campo App Name não foi encontrado em project.properties. Tentando encontrar em arquivos .scm...")
118
  app_name = extract_app_name_from_scm_files(temp_dir)
 
153
  return media_files
154
 
155
  def list_components_in_aia_file(file_path):
156
+
157
  results_df = pd.DataFrame(columns=[
158
  'aia_file', 'project_info', 'components', 'IA components', 'screens', 'operators',
159
  'variables', 'events', 'extensions', 'Media',
 
162
 
163
  pd.set_option('display.max_colwidth', None)
164
  file_name = os.path.basename(file_path)
165
+
166
 
167
  components_list = []
168
  number_of_screens = 0
169
  operators_count = 0
170
  variables_count = 0
171
+ events_count = 0
172
+
173
  media_files = extract_media_files(file_path)
174
  media_summary = ', '.join(media_files)
175
+
176
  project_info = extract_project_info_from_properties(file_path)
177
  project_info_str = f"Timestamp: {project_info['timestamp']}, App Name: {project_info['app_name']}, Version: {project_info['app_version']}, AuthURL: {project_info['authURL']}"
178
 
 
181
  with ZipFile(file_path, 'r') as zip_ref:
182
  zip_ref.extractall(temp_dir)
183
  scm_files = glob.glob(temp_dir + '/src/appinventor/*/*/*.scm')
184
+ bky_files = glob.glob(temp_dir + '/src/appinventor/*/*/*.bky')
185
 
186
  number_of_screens = len(scm_files)
187
  for scm_file in scm_files:
 
192
  operators_count += len(re.findall(r'[+\-*/<>!=&|]', content))
193
  variables_count += len(re.findall(r'"\$Name":"(.*?)"', content))
194
 
195
+
196
  drawing_and_animation_summary = ', '.join(extract_category_components(components_list, drawing_and_animation_patterns))
197
  maps_summary = ', '.join(extract_category_components(components_list, maps_patterns))
198
  sensors_summary = ', '.join(extract_category_components(components_list, sensors_patterns))
 
201
  connectivity_summary = ', '.join(extract_category_components(components_list, connectivity_patterns))
202
 
203
 
204
+
205
+
206
  extensions_list = []
207
  extensions_list = extract_extensions_from_aia(file_path)
208
 
 
210
  with open(bky_file, 'r', encoding='utf-8', errors='ignore') as file:
211
  bky_content = file.read()
212
  events_count += count_events_in_bky_file(bky_content)
213
+
214
 
215
 
216
+
217
  extensions_summary = ', '.join(list(set(extensions_list)))
218
 
219
  components_count = collections.Counter(components_list)
 
238
  'Connectivity': connectivity_summary
239
  }])
240
 
241
+
242
  results_df = pd.concat([results_df, new_row], ignore_index=True)
243
  return results_df
244
  #
245
 
246
+
 
247
  output_style = """
248
  <style>
249
  .output-container {
 
263
  </style>
264
  """
265
 
266
+
267
  def analyze_aia(uploaded_file):
268
  try:
269
+
270
  file_path = uploaded_file.name if hasattr(uploaded_file, 'name') else None
271
 
272
  if file_path and os.path.exists(file_path):
 
274
  with tempfile.TemporaryDirectory() as temp_dir:
275
  zip_ref.extractall(temp_dir)
276
  results_df = list_components_in_aia_file(file_path)
277
+
278
  html_result = results_df.to_html(escape=False, classes="output-html")
279
  return output_style + f'<div class="output-container">{html_result}</div>'
280
 
 
294
  outputs=gr.HTML(),
295
  title="AIA-Scope",
296
  description="Upload an .aia file to analyze its components.",
297
+ live=False
298
  )
299
 
300
  if __name__ == "__main__":