Skip to content

Commit a52cb11

Browse files
Merge pull request #880 from microsoft/PSL-US-33784
fix: Improve Code Quality issues
2 parents d5ad80d + 3a015be commit a52cb11

25 files changed

Lines changed: 1229 additions & 1243 deletions

docs/workshop/docs/workshop/Challenge-5/python/utility.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def schema_to_tool(schema: Any):
242242
return json.loads(
243243
assistant_message.tool_calls[0].function.arguments, strict=False
244244
)
245-
except:
245+
except Exception:
246246
return assistant_message.tool_calls[0].function.arguments
247247

248248
def get_structured_output_answer(
@@ -348,7 +348,6 @@ def generate_scenes(
348348
scene_generation_prompt = Template(SCENE_GENERATION_PROMPT).substitute(
349349
descriptions=next_segment_content
350350
)
351-
scence_response = VideoSceneResponse(scenes=[])
352351
scence_response = openai_assistant.get_structured_output_answer(
353352
"", scene_generation_prompt, VideoSceneResponse
354353
)
@@ -433,7 +432,6 @@ def generate_chapters(
433432
chapter_generation_prompt = Template(CHAPTER_GENERATION_PROMPT).substitute(
434433
descriptions=scene_descriptions
435434
)
436-
chapter_response = VideoChapterResponse(chapters=[])
437435
chapter_response = openai_assistant.get_structured_output_answer(
438436
"", chapter_generation_prompt, VideoChapterResponse
439437
)
@@ -460,7 +458,6 @@ def aggregate_tags(
460458
tags_dedup = set(map(lambda x: re.sub(r'^ ', '', x), tags))
461459
tag_dedup_prompt = Template(DEDUP_PROMPT).substitute(tag_list=tags_dedup)
462460

463-
tag_response = VideoTagResponse(tags=[])
464461
tag_response = openai_assistant.get_structured_output_answer(
465462
"", tag_dedup_prompt, VideoTagResponse
466463
)

infra/scripts/fabric_scripts/create_fabric_items.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
from azure.identity import ManagedIdentityCredential
21
import base64
32
import json
43
import requests
5-
import pandas as pd
64
import os
75
from glob import iglob
86
import zipfile
@@ -98,11 +96,11 @@
9896
# upload extracted folder
9997
file_names = [f for f in iglob(os.path.join(local_path, "**", "*"), recursive=True) if os.path.isfile(f)]
10098
# print('file_names ex', file_names)
101-
for file_name in file_names:
102-
upload_file_name = os.path.basename(file_name)
99+
for extracted_file in file_names:
100+
upload_file_name = os.path.basename(extracted_file)
103101
file_client = directory_client.get_file_client("cu_audio_files_all/" + upload_file_name)
104-
# with open(file=os.path.join(extract_dir, file_name), mode="rb") as data:
105-
with open(file=file_name, mode="rb") as data:
102+
# with open(file=os.path.join(extract_dir, extracted_file), mode="rb") as data:
103+
with open(file=extracted_file, mode="rb") as data:
106104
# print('data', data)
107105
file_client.upload_data(data, overwrite=True)
108106

@@ -127,7 +125,7 @@
127125
env_res = requests.get(fabric_env_url, headers=fabric_headers)
128126
env_res_id = env_res.json()['value'][0]['id']
129127
# print(env_res.json())
130-
except:
128+
except Exception: # Environments may not be provisioned yet
131129
env_res_id = ''
132130

133131
#create notebook items
@@ -150,14 +148,14 @@
150148
notebook_json['metadata']['dependencies']['lakehouse']['default_lakehouse'] = lakehouse_res.json()['id']
151149
notebook_json['metadata']['dependencies']['lakehouse']['default_lakehouse_name'] = lakehouse_res.json()['displayName']
152150
notebook_json['metadata']['dependencies']['lakehouse']['default_lakehouse_workspace_id'] = lakehouse_res.json()['workspaceId']
153-
except:
151+
except Exception: # Lakehouse metadata may not be available
154152
pass
155153

156154
if env_res_id != '':
157155
try:
158156
notebook_json['metadata']['dependencies']['environment']['environmentId'] = env_res_id
159157
notebook_json['metadata']['dependencies']['environment']['workspaceId'] = lakehouse_res.json()['workspaceId']
160-
except:
158+
except Exception: # Environment metadata may not be available
161159
pass
162160

163161

@@ -178,8 +176,7 @@
178176
}
179177
}
180178

181-
fabric_response = requests.post(fabric_items_url, headers=fabric_headers, json=notebook_data)
182-
#print(fabric_response.json())
179+
requests.post(fabric_items_url, headers=fabric_headers, json=notebook_data)
183180

184181
time.sleep(120)
185182

infra/scripts/index_scripts/02_create_cu_template_audio.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
analyzer = client.get_analyzer_detail_by_id(ANALYZER_ID)
3737
if analyzer is not None:
3838
client.delete_analyzer(ANALYZER_ID)
39-
except Exception:
39+
except Exception: # Analyzer may not exist yet, safe to ignore
4040
pass
4141

4242
response = client.begin_create_analyzer(ANALYZER_ID, analyzer_template_path=ANALYZER_TEMPLATE_FILE)

infra/scripts/index_scripts/02_create_cu_template_text.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
analyzer = client.get_analyzer_detail_by_id(ANALYZER_ID)
3232
if analyzer is not None:
3333
client.delete_analyzer(ANALYZER_ID)
34-
except Exception:
34+
except Exception: # Analyzer may not exist yet, safe to ignore
3535
pass
3636

3737
response = client.begin_create_analyzer(ANALYZER_ID, analyzer_template_path=ANALYZER_TEMPLATE_FILE)

infra/scripts/index_scripts/03_cu_process_data_text.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -381,10 +381,10 @@ async def process_files():
381381

382382
docs.extend(await prepare_search_doc(content, conversation_id, path.name, embeddings_client))
383383
counter += 1
384-
except Exception:
384+
except Exception: # Skip files that fail processing
385385
pass
386386
if docs != [] and counter % 10 == 0:
387-
result = search_client.upload_documents(documents=docs)
387+
search_client.upload_documents(documents=docs)
388388
docs = []
389389
if docs:
390390
search_client.upload_documents(documents=docs)
@@ -533,7 +533,6 @@ async def call_topic_mining_agent(topics_str1):
533533
column_names = [i[0] for i in cursor.description]
534534
df_topics = pd.DataFrame(rows, columns=column_names)
535535
mined_topics_list = df_topics['label'].tolist()
536-
mined_topics = ", ".join(mined_topics_list)
537536
print(f"✓ Mined {len(mined_topics_list)} topics")
538537

539538
async def call_topic_mapping_agent(agent, input_text, list_of_topics):

infra/scripts/index_scripts/04_cu_process_custom_data.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def create_search_index():
190190
connection_string = f"DRIVER={driver};SERVER={SQL_SERVER};DATABASE={SQL_DATABASE};"
191191
conn = pyodbc.connect(connection_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct})
192192
cursor = conn.cursor()
193-
except:
193+
except Exception: # Fall back to ODBC Driver 17
194194
driver = "{ODBC Driver 17 for SQL Server}"
195195
token_bytes = credential.get_token("https://database.windows.net/.default").token.encode("utf-16-LE")
196196
token_struct = struct.pack(f"<I{len(token_bytes)}s", len(token_bytes), token_bytes)
@@ -435,10 +435,10 @@ async def process_files():
435435

436436
docs.extend(await prepare_search_doc(content, conversation_id, path.name, embeddings_client))
437437
counter += 1
438-
except Exception:
438+
except Exception: # Skip files that fail processing
439439
pass
440440
if docs != [] and counter % 10 == 0:
441-
result = search_client.upload_documents(documents=docs)
441+
search_client.upload_documents(documents=docs)
442442
docs = []
443443
if docs:
444444
search_client.upload_documents(documents=docs)
@@ -469,7 +469,6 @@ async def process_files():
469469
conversation_id = file_name.split('convo_', 1)[1].split('_')[0]
470470
conversationIds.append(conversation_id)
471471

472-
duration = int(result['result']['contents'][0]['fields']['Duration']['valueString'])
473472
fields = result['result']['contents'][0]['fields']
474473
duration_str = get_field_value(fields, 'Duration', '0')
475474
try:
@@ -507,9 +506,9 @@ async def process_files():
507506
docs.extend(await prepare_search_doc(content, document_id, path.name, embeddings_client))
508507
counter += 1
509508
except Exception:
510-
pass
509+
pass # Skip files that fail to process
511510
if docs != [] and counter % 10 == 0:
512-
result = search_client.upload_documents(documents=docs)
511+
search_client.upload_documents(documents=docs)
513512
docs = []
514513

515514
# upload the last batch
@@ -620,8 +619,6 @@ async def call_topic_mining_agent(topics_str1):
620619
res = res.replace("```json", '').replace("```", '').strip()
621620
return json.loads(res)
622621

623-
MAX_TOKENS = 3096
624-
625622
res = asyncio.run(call_topic_mining_agent(topics_str))
626623
for object1 in res['topics']:
627624
cursor.execute("INSERT INTO km_mined_topics (label, description) VALUES (?,?)", (object1['label'], object1['description']))
@@ -632,7 +629,6 @@ async def call_topic_mining_agent(topics_str1):
632629
column_names = [i[0] for i in cursor.description]
633630
df_topics = pd.DataFrame(rows, columns=column_names)
634631
mined_topics_list = df_topics['label'].tolist()
635-
mined_topics = ", ".join(mined_topics_list)
636632
print(f"✓ Mined {len(mined_topics_list)} topics")
637633

638634
async def call_topic_mapping_agent(agent, input_text, list_of_topics):

infra/scripts/validate_bicep_params.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def parse_parameters_env_vars(json_path: Path) -> dict[str, list[str]]:
107107
try:
108108
data = json.loads(sanitized)
109109
params = data.get("parameters", {})
110-
except json.JSONDecodeError:
110+
except json.JSONDecodeError: # Parameters file may have azd variable placeholders
111111
pass
112112

113113
# Walk each top-level parameter and scan its entire serialized value

src/App/src/components/ChartFilter/ChartFilter.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ const ChartFilter: React.FC<FilterComponentProps> = (props) => {
3636
(state) => state.dashboards
3737
);
3838
const { applyFilters, fetchingCharts } = props;
39-
const initialDateRange = typeof Array.isArray(selectedFilters.DateRange)
39+
const initialDateRange = Array.isArray(selectedFilters.DateRange)
4040
? selectedFilters.DateRange
4141
: [""];
4242

src/api/common/database/cosmosdb_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async def delete_messages(self, conversation_id, user_id):
115115
item=message["id"], partition_key=user_id
116116
)
117117
response_list.append(resp)
118-
return response_list
118+
return response_list
119119

120120
async def get_conversations(self, user_id, limit, sort_order="DESC", offset=0):
121121
parameters = [{"name": "@userId", "value": user_id}]

src/api/common/database/sqldb_service.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ async def get_db_connection():
6464

6565
if conn is None:
6666
raise RuntimeError("Unable to connect using ODBC Driver 18 or 17 with Azure Credential")
67+
return conn
6768
except Exception as e:
6869
logging.error("Failed with Azure Credential: %s", str(e))
6970
raise RuntimeError("Unable to connect to SQL database using Microsoft Entra authentication.") from e
@@ -179,7 +180,7 @@ async def fetch_chart_data(chart_filters: ChartFilters = ''):
179180
req_body = ''
180181
try:
181182
req_body = chart_filters.model_dump()
182-
except BaseException:
183+
except Exception: # model_dump may fail if filters are empty or invalid
183184
pass
184185
if req_body != '':
185186
where_clause = ''

0 commit comments

Comments
 (0)