import React, { useState } from "react";
import api from "../../api";
import "../../assets/css/style.css";
import ErrorPopup from "../Sections/ErrorPopup";
import VoiceInput from "../Sections/VoiceInput"; // 👈 Make sure you have this component
const Summariser = () => {
const [inputText, setInputText] = useState("");
const [summarizedText, setSummarizedText] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [summaryType, setSummaryType] = useState("paragraph");
const [originalText, setOriginalText] = useState("");
const [errorPopupMessage, setErrorPopupMessage] = useState("");
const token = localStorage.getItem("jwtToken");
const handleSummarize = async () => {
if (!inputText.trim()) {
setError("Please enter text to summarize.");
return;
}
setError("");
setLoading(true);
setSummarizedText("");
setOriginalText("");
try {
const response = await api.summarizeText(
{
text: inputText,
type: summaryType,
},
{ headers: { Authorization: `Bearer ${token}` } },
);
if (response && response.summarized_text) {
const cleanedText = response.summarized_text
.replace(/\n\s*\n/g, "\n")
.replace(/^\s+|\s+$/g, "");
setSummarizedText(cleanedText);
setOriginalText(response.original_text || inputText);
} else {
const message = "No summarized text found.";
setError(message);
setErrorPopupMessage(message);
}
} catch (err) {
const message =
err.message || "Failed to summarize text. Please try again.";
setError(message);
setErrorPopupMessage(
message.includes("504")
? "Server timeout. Please try again. (504 Gateway Timeout)"
: message,
);
} finally {
setLoading(false);
}
};
const handleClearText = () => {
setInputText("");
setSummarizedText("");
setOriginalText("");
setError("");
};
const handleVoiceResult = (transcript) => {
setInputText((prevText) => `${prevText} ${transcript}`.trim());
};
const formatSummaryText = (text) => {
if (!text) return null;
const normalizedText = text
.replace(/\n\s*\n/g, "\n")
.replace(/^\s+|\s+$/g, "");
const paragraphs = normalizedText
.split("\n")
.filter((p) => p.trim().length > 0);
return paragraphs.map((paragraph, index) => (
{paragraph}
}
Original length: {originalText.split(" ").length} words | Summary length: {summarizedText.split(" ").length} words | Reduction:{" "} {Math.round( 100 - (summarizedText.split(" ").length / originalText.split(" ").length) * 100, )} %