Skip to content

Commit 24be5ae

Browse files
Refactor and clean up code across multiple files
1 parent 64ce6c5 commit 24be5ae

36 files changed

+62
-318
lines changed

infra/scripts/index_scripts/02_process_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,6 @@ def prepare_search_doc(content, document_id):
177177
docs = []
178178

179179
if docs != []:
180-
results = search_client.upload_documents(documents=docs)
180+
search_client.upload_documents(documents=docs)
181181

182182
print(f'{str(counter)} files processed.')

scripts/data_utils.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,13 @@ def extract_caption(self, text):
157157

158158
def mask_urls_and_imgs(self, text) -> Tuple[Dict[str, str], str]:
159159
def find_urls(string):
160-
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^()\s<>]+|\(([^()\s<>]+|(\([^()\s<>]+\)))*\))+(?:\(([^()\s<>]+|(\([^()\s<>]+\)))*\)|[^()\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
160+
regex = (
161+
r"(?i)\b("
162+
r"(?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)"
163+
r"(?:[^()\s<>]+|\(([^()\s<>]+|(\([^()\s<>]+\)))*\))+"
164+
r"(?:\(([^()\s<>]+|(\([^()\s<>]+\)))*\)|[^()\s`!()\[\]{};:'\".,<>?«»“”‘’])"
165+
r")"
166+
)
161167
urls = re.findall(regex, string)
162168
return [x[0] for x in urls]
163169

@@ -693,7 +699,9 @@ def extract_pdf_content(file_path, form_recognizer_client, use_layout=False):
693699
page_map = []
694700
model = "prebuilt-layout" if use_layout else "prebuilt-read"
695701

696-
base64file = base64.b64encode(open(file_path, "rb").read()).decode()
702+
with open(file_path, "rb") as f:
703+
file_bytes = f.read()
704+
base64file = base64.b64encode(file_bytes).decode()
697705
poller = form_recognizer_client.begin_analyze_document(
698706
model, AnalyzeDocumentRequest(bytes_source=base64file)
699707
)
@@ -1048,7 +1056,8 @@ def image_content_to_tag(image_content: str) -> str:
10481056

10491057

10501058
def get_caption(image_path, captioning_model_endpoint, captioning_model_key):
1051-
encoded_image = base64.b64encode(open(image_path, "rb").read()).decode("ascii")
1059+
with open(image_path, "rb") as image_file:
1060+
encoded_image = base64.b64encode(image_file.read()).decode("ascii")
10521061
file_ext = image_path.split(".")[-1]
10531062
headers = {
10541063
"Content-Type": "application/json",

src/.env.sample

Lines changed: 0 additions & 131 deletions
This file was deleted.

src/app.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,6 @@ async def init_ai_foundry_client():
167167
return ai_foundry_client
168168
except Exception as e:
169169
logging.exception("Exception in AI Foundry initialization", e)
170-
ai_foundry_client = None
171170
raise e
172171

173172

@@ -197,7 +196,6 @@ def init_cosmosdb_client():
197196
if span is not None:
198197
span.record_exception(e)
199198
span.set_status(Status(StatusCode.ERROR, str(e)))
200-
cosmos_conversation_client = None
201199
raise e
202200
else:
203201
logging.debug("CosmosDB not configured")

src/backend/history/cosmosdbservice.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ async def delete_messages(self, conversation_id, user_id):
110110
item=message["id"], partition_key=user_id
111111
)
112112
response_list.append(resp)
113-
return response_list
113+
return response_list
114114

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

src/backend/settings.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,9 @@ def split_contexts(
249249
class DatasourcePayloadConstructor(BaseModel, ABC):
250250
_settings: "_AppSettings" = PrivateAttr()
251251

252-
def __init__(self, settings: "_AppSettings", **data):
253-
super().__init__(**data)
252+
def __init__(self, *args, settings: "_AppSettings", **data):
253+
# Call next __init__ in MRO to allow cooperative multiple inheritance
254+
super().__init__(*args, **data)
254255
self._settings = settings
255256

256257
@abstractmethod
@@ -274,6 +275,9 @@ class _AzureSearchSettings(BaseSettings, DatasourcePayloadConstructor):
274275
endpoint_suffix: str = Field(default="search.windows.net", exclude=True)
275276
connection_name: Optional[str] = None
276277
index: str = Field(serialization_alias="index_name")
278+
def __init__(self, settings: "_AppSettings", **data):
279+
# Ensure both BaseSettings and DatasourcePayloadConstructor are initialized
280+
super().__init__(settings=settings, **data)
277281
key: Optional[str] = Field(default=None, exclude=True)
278282
use_semantic_search: bool = Field(default=False, exclude=True)
279283
semantic_search_config: str = Field(
@@ -439,6 +443,7 @@ def set_datasource_settings(self) -> Self:
439443
logging.warning(
440444
"No datasource configuration found in the environment -- calls will be made to Azure OpenAI without grounding data."
441445
)
446+
return self
442447

443448

444449
app_settings = _AppSettings()

src/frontend/__mocks__/react-markdown.tsx

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,9 @@
22

33
import React from 'react';
44

5-
// Mock implementation of react-markdown
6-
const mockNode = {
7-
children: [{ value: 'console.log("Test Code");' }]
8-
};
9-
const mockProps = { className: 'language-javascript' };
10-
115
const ReactMarkdown: React.FC<{ children: React.ReactNode , components: any }> = ({ children,components }) => {
126
return <div data-testid="reactMockDown">
13-
{/* {components && components.code({ node: mockNode, ...mockProps })} */}
7+
{/* {components && components.code({ node: { children: [{ value: 'console.log("Test Code");' }] }, ...mockProps })} */}
148
{children}</div>; // Simply render the children
159
};
1610

src/frontend/src/api/models.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import Plotly from 'react-plotly.js'
2-
31
export type AskResponse = {
42
answer: string
53
citations: Citation[]

src/frontend/src/components/Answer/Answer.test.tsx

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
import { renderWithContext, screen, waitFor, fireEvent, act, logRoles } from '../../test/test.utils';
1+
import { renderWithContext, screen, waitFor, fireEvent, act } from '../../test/test.utils';
22
import { Answer } from './Answer'
3-
import { AppStateContext } from '../../state/AppProvider'
43
import {AskResponse, Citation, Feedback, historyMessageFeedback } from '../../api';
54
//import { Feedback, AskResponse, Citation } from '../../api/models'
65
import { cloneDeep } from 'lodash'
76
import userEvent from '@testing-library/user-event';
8-
import { CitationPanel } from '../../pages/chat/Components/CitationPanel';
97

108
// Mock required modules and functions
119
jest.mock('../../api/api', () => ({
@@ -27,9 +25,6 @@ jest.mock('remark-gfm', () => jest.fn());
2725
jest.mock('rehype-raw', () => jest.fn());
2826
jest.mock('remark-supersub', () => jest.fn());
2927

30-
const mockDispatch = jest.fn();
31-
const mockOnCitationClicked = jest.fn();
32-
3328
// Mock context provider values
3429
let mockAppState = {
3530
frontendSettings: { feedback_enabled: true, sanitize_answer: true },
@@ -360,15 +355,14 @@ describe('Answer Component', () => {
360355
it('should open and submit negative feedback dialog', async () => {
361356
userEvent.setup();
362357
renderComponent();
363-
const handleChange = jest.fn();
364358
const dislikeButton = screen.getByLabelText('Dislike this response');
365359

366360
// Click dislike to open dialog
367361
await fireEvent.click(dislikeButton);
368362
expect(screen.getByText("Why wasn't this response helpful?")).toBeInTheDocument();
369363

370364
// Select feedback and submit
371-
const checkboxEle = await screen.findByLabelText(/Citations are wrong/i)
365+
const checkboxEle = await screen.findByLabelText(/Citations are wrong/i);
372366
//logRoles(checkboxEle)
373367
await waitFor(() => {
374368
userEvent.click(checkboxEle);
@@ -382,12 +376,8 @@ describe('Answer Component', () => {
382376

383377
it('calls resetFeedbackDialog and setFeedbackState with Feedback.Neutral on dialog dismiss', async () => {
384378

385-
const resetFeedbackDialogMock = jest.fn();
386-
const setFeedbackStateMock = jest.fn();
387-
388379
userEvent.setup();
389380
renderComponent();
390-
const handleChange = jest.fn();
391381
const dislikeButton = screen.getByLabelText('Dislike this response');
392382

393383
// Click dislike to open dialog
@@ -410,7 +400,6 @@ describe('Answer Component', () => {
410400
it('Dialog Options should be able to select and unSelect', async () => {
411401
userEvent.setup();
412402
renderComponent();
413-
const handleChange = jest.fn();
414403
const dislikeButton = screen.getByLabelText('Dislike this response');
415404

416405
// Click dislike to open dialog
@@ -419,15 +408,15 @@ describe('Answer Component', () => {
419408
expect(screen.getByText("Why wasn't this response helpful?")).toBeInTheDocument();
420409

421410
// Select feedback and submit
422-
const checkboxEle = await screen.findByLabelText(/Citations are wrong/i)
411+
const checkboxEle = await screen.findByLabelText(/Citations are wrong/i);
423412
expect(checkboxEle).not.toBeChecked();
424413

425414
await userEvent.click(checkboxEle);
426415
await waitFor(() => {
427416
expect(checkboxEle).toBeChecked();
428417
});
429418

430-
const checkboxEle1 = await screen.findByLabelText(/Citations are wrong/i)
419+
const checkboxEle1 = await screen.findByLabelText(/Citations are wrong/i);
431420

432421
await userEvent.click(checkboxEle1);
433422
await waitFor(() => {
@@ -439,7 +428,6 @@ describe('Answer Component', () => {
439428
it('Should able to show ReportInappropriateFeedbackContent form while click on "InappropriateFeedback" button ', async () => {
440429
userEvent.setup();
441430
renderComponent();
442-
const handleChange = jest.fn();
443431
const dislikeButton = screen.getByLabelText('Dislike this response');
444432

445433
// Click dislike to open dialog
@@ -514,7 +502,6 @@ describe('Answer Component', () => {
514502
feedbackState: { '123': Feedback.OtherHarmful },
515503
}
516504
renderComponent(answerWithMissingFeedback, extraMockState);
517-
const handleChange = jest.fn();
518505
const dislikeButton = screen.getByLabelText('Dislike this response');
519506

520507
// Click dislike to open dialog
@@ -529,10 +516,6 @@ describe('Answer Component', () => {
529516

530517
tempMockCitation[0].filepath = '';
531518
tempMockCitation[0].reindex_id = '';
532-
const answerWithMissingFeedback = {
533-
...mockAnswerProps,
534-
CitationPanel: [...tempMockCitation]
535-
}
536519

537520
renderComponent();
538521

src/frontend/src/components/Answer/Answer.tsx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ export const Answer = ({ answer, onCitationClicked }: Props) => {
3939
}
4040

4141
const [isRefAccordionOpen, { toggle: toggleIsRefAccordionOpen }] = useBoolean(false)
42-
const filePathTruncationLimit = 50
4342

4443
const parsedAnswer = useMemo(() => parseAnswer(answer), [answer])
4544
const [chevronIsExpanded, setChevronIsExpanded] = useState(isRefAccordionOpen)
@@ -156,7 +155,7 @@ export const Answer = ({ answer, onCitationClicked }: Props) => {
156155
const onLikeResponseClicked = async () => {
157156
if (answer.message_id == undefined) return
158157

159-
let newFeedbackState = feedbackState
158+
let newFeedbackState: Feedback.Neutral | Feedback.Positive | Feedback.Negative
160159
// Set or unset the thumbs up state
161160
if (feedbackState == Feedback.Positive) {
162161
newFeedbackState = Feedback.Neutral
@@ -176,7 +175,7 @@ export const Answer = ({ answer, onCitationClicked }: Props) => {
176175
const onDislikeResponseClicked = async () => {
177176
if (answer.message_id == undefined) return
178177

179-
let newFeedbackState = feedbackState
178+
let newFeedbackState: Feedback.Neutral | Feedback.Negative
180179
if (feedbackState === undefined || feedbackState === Feedback.Neutral || feedbackState === Feedback.Positive) {
181180
newFeedbackState = Feedback.Negative
182181
setFeedbackState(newFeedbackState)

0 commit comments

Comments
 (0)