Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add file upload and custom metric #17

Merged
merged 1 commit into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions app/actions/sustainabilityReport/extractQAPairs.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,44 @@
import { Company, ExtractQAResult, SustainabilityMetric } from '@/app/types/SustainabilityTypes';
import { Report, ExtractQAResult, SustainabilityMetric } from '@/app/types/SustainabilityTypes';

interface IParams {
company: Company;
report: Report;
metrics: SustainabilityMetric[];
}

const extractQAPairs = async ({ company, metrics }: IParams): Promise<ExtractQAResult> => {
console.log('Extracting QA for company:', company.companyName);
const extractQAPairs = async ({ report, metrics }: IParams): Promise<ExtractQAResult> => {
console.log('Extracting QA for report:', report.sustainabilityReport.name);
console.log('Metrics:', metrics);

const qaPairs: Record<string, string>[] = [];
const fileResponse = await fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH}sustainability-reports/${company.sustainabilityReport}`
);
const fileContent = await fileResponse.text();

// Convert File object to text
const fileContent = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsText(report.sustainabilityReport);
});

for (const metric of metrics) {
let answerStartIndex = fileContent.indexOf(metric.question);
if (answerStartIndex === -1) {
console.log('no answer found for:', metric.question);
console.log('No answer found for:', metric.question);
continue;
}
answerStartIndex += metric.question.length;
const answerContent = fileContent.slice(answerStartIndex);

// Regular expression to match the question pattern
const pattern: RegExp = /^C\d{1,2}\.\d{1,2}[a-z]?/m;

// Split the answer content into segments based on the pattern
const segments: string[] = answerContent.split(pattern);
const answer = segments[0].trim();
console.log(`answer found for ${metric.question}:`, answer);
console.log(`Answer found for ${metric.question}:`, answer);
qaPairs.push({ [metric.name]: answer });
}
const response: ExtractQAResult = { status: 200, error: null, result: { qaPairs } };

const response: ExtractQAResult = { status: 200, error: null, result: { qaPairs } };
return response;
};

Expand Down
64 changes: 64 additions & 0 deletions app/components/SustainabilityReport/Dropzone.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { useDropzone } from 'react-dropzone';
import { CloudArrowUp } from '@phosphor-icons/react';
import { useCallback, useState } from 'react';
import useSustainabilityStore from '@/app/hooks/sustainabilityReport/useSustainabilityStore';
import { GenerationStatus, Report } from '@/app/types/SustainabilityTypes';
const iconContainerClasses = 'flex items-center justify-center text-3xl mb-4';
const allowedTypes = ['text/plain'];

const Dropzone = () => {
const { addReports, addReportsToAdd } = useSustainabilityStore();
const [error, setError] = useState<string>('');

const onDrop = useCallback(
async (acceptedFiles: File[]) => {
for (const file of acceptedFiles) {
if (file) {
if (!allowedTypes.includes(file.type)) {
setError(`Error processing ${file.name}: File type is not supported.`);
return;
}
if (file.size > 10 * 1024 * 1024) {
setError(`Error processing ${file.name}: Size exceeds the limit of 10 MB. Please try again.`);
return;
}
}
}

const newReports: Report[] = [];
acceptedFiles.forEach((file) => {
const newReport: Report = {
sustainabilityReport: file,
reportResults: {},
status: GenerationStatus.READY,
};
newReports.push(newReport);
});
addReportsToAdd(newReports);
},
[addReports]
);

const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

return (
<div className="flex flex-col w-full h-full items-center justify-center">
<div
className={`border-2 ${error ? 'border-red-400' : 'border-gray-300'} bg-gray-100 border-dashed h-[25vh] rounded-md text-center cursor-pointer transition duration-300 ease-in-out flex flex-col items-center justify-center hover:border-gray-500 w-full`}
{...getRootProps()}
>
<div className={iconContainerClasses}>{<CloudArrowUp size={32} />}</div>
<input {...getInputProps()} className="hidden" />
<p className="mt-2">
{isDragActive ? 'Drop files here' : 'Drag and drop files here, or click to select files'}
</p>
<p className="text-sm text-gray-500">TXT files of CDP Reports only</p>
<p className="text-sm text-gray-500">Please do not upload any sensitive information.</p>
<p className="text-sm text-gray-500">Max 10 MB</p>
</div>
{error && <p className="text-red-400 mt-2">{error}</p>}
</div>
);
};

export default Dropzone;
94 changes: 0 additions & 94 deletions app/components/modals/SustainabilityCompanyModal.tsx

This file was deleted.

Loading
Loading