File size: 16,892 Bytes
862b14b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import Navbar from "./Components/Navbar";
import axios from "axios";
import YouTube from "react-youtube";
import ReactMarkdown from "react-markdown";
// import { fetchTranscript } from "youtube-subtitle-transcript";
// import Mindmap from "./Components/Mindmap";
import ForceGraph2D from "react-force-graph-2d";
import ForceGraph3D from "react-force-graph-3d";
import SpriteText from "three-spritetext";
function App() {
const { useRef } = React;
const fgRef = useRef();
const navigate = useNavigate();
const [messages, setMessages] = useState([]);
const [userInput, setUserInput] = useState("");
const [timestamps, setTimestamps] = useState([]);
const [transcript, setTranscript] = useState("");
const [loading, setLoading] = useState(false);
const [transcriptStatus, setTranscriptStatus] = useState(false);
const location = useLocation();
const videoLink = location.state?.videoLink;
const metaData = location.state?.metaData;
const [videoId, setVideoId] = useState("");
const endOfMessagesRef = useRef(null);
const [player, setPlayer] = React.useState(null);
const routebody = "http://localhost:5000";
const handleClick = async () => {
if (!loading) {
try {
const response = await axios.post(routebody.concat("/transcript"));
// console.log("Transcript", response.data.transcript);
const temp = response.data.transcript; // This should now correctly reflect the updated state
// console.log("Tt", temp);
const element = document.createElement("a");
const file = new Blob([temp], { type: "text/plain" }); // Use the fetched transcript directly
element.href = URL.createObjectURL(file);
element.download = "transcript.txt";
document.body.appendChild(element); // Required for this to work in FireFox
element.click();
} catch (error) {
window.alert("Failed to fetch transcript:", error);
}
}
};
const fetch = async () => {
try {
setTranscript(response.data.transcript);
setTranscriptStatus(response.data.status);
} catch (error) {
console.error("Failed to fetch transcript:", error);
}
};
const onPlayerReady = (event) => {
setPlayer(event.target);
console.log("Player is ready");
};
const scrollToBottom = () => {
if (endOfMessagesRef.current) {
endOfMessagesRef.current.scrollIntoView({ behavior: "smooth" });
}
};
useEffect(() => {
scrollToBottom();
}, [messages]);
console.log(videoLink);
useEffect(() => {
function convertToEmbedUrl(watchUrl) {
return watchUrl.replace("/watch?v=", "/embed/");
}
if (videoLink) {
setVideoId(videoLink.split("v=")[1]);
console.log(videoId);
} else {
setVideoId("dQw4w9WgXcQ") // Easter Egg π₯
// navigate("/");
}
}, []);
const sendMessage = async () => {
try {
console.log("Sending message...");
setLoading(true);
let formattedMessages = [];
for (let i = 0; i < messages.length; i += 2) {
let message = [];
message.push(messages[i].content);
message.push(messages[i + 1].content);
formattedMessages.push(message);
}
console.log("Formatted", formattedMessages);
// const formattedInput =
// userInput +
// "?. In bulleted points, respond with the key points of the answer for the question and provide a concise answer in markdown format highlighting the keypoints and features using markdown.";
const response = await axios.post(routebody.concat("/response"), {
query: userInput,
chat_history: formattedMessages,
});
console.log("Answer", response.data.answer);
console.log("Time sta", response.data.timestamps);
setTimestamps(response.data.timestamps.slice(0, 5));
setMessages([
...messages,
{ role: "user", content: userInput + "?" },
{ role: "assistant", content: response.data.answer },
]);
console.log(messages);
setUserInput("");
setLoading(false);
} catch (error) {
console.log(error);
}
};
const handleKeyPress = (e) => {
if (e.key === "Enter" && userInput.trim() !== "") {
sendMessage();
e.preventDefault(); // To prevent any default behavior, such as a line break in a textarea
}
};
const markdown = "";
useEffect(() => {
async function fetchSummary() {
try {
console.log("Summarizing...");
setLoading(true);
const response = await axios.post(routebody.concat("/response"), {
query:
`You are a Intelligent Tutor. Your task is to smartly summarize the the Youtube video transcript provided as context. \
Don't mention the transcript as 'transcript' but refer to it as Youtube video or just video while having a conversation with a student.\
Give me in-depth response for the summaray part only... something like : Short-Intro to what is being said in the video transcript.\
5 - KEY points to understand in bullet point format... Conclusion as to what can be learnt from this video transcript....\
Only the Conclusion in the summary should be application perspective.... \ Also you are a friendly tutor, so if the question asked is casual or something not realted to the video transcript then answer it casually like a friend,
only if the question asked is casual or not realted to the context... more of general question ... only then you do this ... other wise stick to the context provided...
From thsi point provide all the responses in this chat in Markdown Format highlighting keypoints and fetures. Also for every response you have to give introduction, keypoints and conclusion. Keep in mind that the markdown syntax should be followed for every response that you will give in fututre.`,
chat_history: "",
});
console.log("Answer", response.data.answer);
console.log("Time stamp", response.data.timestamps);
// setTimestamps(response.data.timestamps);
// only set first five timestamps
setTimestamps(response.data.timestamps.slice(0, 5));
setMessages([
...messages,
{ role: "user", content: userInput },
{ role: "assistant", content: response.data.answer },
]);
console.log(messages);
setUserInput("");
setLoading(false);
} catch (error) {
console.log(error);
}
}
return () => {
// fetch
fetchSummary();
}
}, []);
// /////////////// data for mindmap ///////////////////////
const [data, setData] = useState();
useEffect(() => {
async function fetchMindMap() {
try {
console.log("Mind Mapping...");
setLoading(true);
const response = await axios.post(routebody.concat("/response"), {
query:
`Smart Tutor, please provide a consize creative Mind Map!... The Idea is to Show an intricate, easy to understand (in terms of concept "linking") mind map, based on the provided context\
so that the users can understand the video --key contepts-- helping them to know what the video is discussing in-depth!, remember not to over simplifiy the mind-map,\
WE can have beautiful looking mind map with branches of important points from the video...
We want your response in json object for example: \
{
"nodes": [
{
"id": "Main Concept",
"group": 1,
"size": 30
},
{
"id": "Sub-Concept 1",
"group": 2,
"size": 20
},
{
"id": "Sub-Concept 2",
"group": 2,
"size": 20
},
{
"id": "Sub-Concept 3",
"group": 2,
"size": 20
},
{
"id": "Sub-Concept 4",
"group": 2,
"size": 20
},
{
"id": "Sub-Concept 5",
"group": 2,
"size": 20
},
{
"id": "Sub-Concept 6",
"group": 2,
"size": 20
},
{
"id":"Sub-Sub-Concept 7",
"group":2,
"size": 15
}
],
"links": [
{
"source": "Main Concept",
"target": "Sub-Concept 1",
"value": 10
},
{
"source": "Main Concept",
"target": "Sub-Concept 2",
"value": 9
},
{
"source": "Main Concept",
"target": "Sub-Concept 3",
"value": 8
},
{
"source": "Main Concept",
"target": "Sub-Concept 4",
"value": 7
},
{
"source": "Main Concept",
"target": "Sub-Concept 5",
"value": 6
},
{
"source": "Main Concept",
"target": "Sub-Concept 6",
"value": 5
},
{
"source": "Sub-Concept 6",
"target": "Sub-Sub-Concept 7",
"value": 5
}
]
}
This structure can be used as a template or guide to create more specific mind maps based on the requirements of the youtube video transcript provided. You can customize the node names, group assignments, and link weights to reflect the content and relationships in your mind map.
only json object of mindmap is expected as output`,
chat_history: "",
});
console.log("MindMap: ", response.data.answer);
setData(JSON.parse(response.data.answer));
setLoading(false);
} catch (error) {
console.log(error);
}
}
// fetchMindMap();
return () => {
// fetch
fetchMindMap();
}
}, []);
// /////////////// data for mindmap ///////////////////////
const CameraOrbit = () => {
return (
<ForceGraph3D
ref={fgRef}
graphData={data}
// dynamically give width and height based on vh and vw
width={window.innerWidth/2 -20}
height={window.innerHeight/3}
nodeAutoColorBy="id"
backgroundColor="#f5f5f5"
// nodeLabel={(node) => `${node.name}`}
// nodeVal={(node) => 2}
nodeThreeObject={(node) => {
const sprite = new SpriteText(node.id);
sprite.color = node.color;
sprite.textHeight = 8;
return sprite;
}}
linkColor={() => "black"}
linkDirectionalParticleColor={() => "red"}
linkDirectionalParticleWidth={6}
linkHoverPrecision={10}
onLinkClick={(link) => fgRef.current.emitParticle(link)}
// reset position of camera on double click
onNodeClick={(node) => {
fgRef.current.centerAt(node.x, node.y, node.z, 1000);
}
}
/>
);
};
const downloadMindmapSVG = () => {
console.log("Downloading SVG")
const svg = fgRef.current.exportSVG();
const blob = new Blob([svg], { type: "image/svg+xml" });
const url = URL.createObjectURL(blob);
const a = document.createElement
("a");
a.href = url;
a.download = "mindmap.svg";
a.click();
URL.revokeObjectURL(url);
}
return (
<div id="App" className="w-full h-screen">
<div>
<Navbar />
</div>
<div id="chat-ui" className="grid grid-cols-2 divide-x-2 h-5/6">
<div className="flex flex-col lg:col-span-1 col-span-2">
<div className=" w-full h-80 justify-center items-center">
<h1 className="text-gray-800 font-semibold text-2xl ml-2 mt-2">
{metaData}
</h1>
<YouTube
className="flex w-full h-full p-2 justify-center items-center"
videoId={videoId}
opts={{
width: "100%",
height: "100%",
playerVars: {
autoplay: 0,
start: 40,
},
}}
onReady={onPlayerReady}
/>
{/* <div className="flex justify-center items-center mt-2">
<button
className={`px-2.5 py-2.5 bg-indigo-600 text-white rounded-md font-semibold text-lg hover:bg-indigo-700 focus:outline-none focus:ring ${
loading && "cursor-not-allowed opacity-35 "
}`}
disabled={loading}
onClick={handleClick}
>
Download transcript. π₯
</button>
</div> */}
<div className="ml-2">
{/* <h1>
Mindmap
</h1> */}
<button
className={`px-2.5 py-2.5 bg-indigo-600 text-white rounded-md font-semibold text-lg hover:bg-indigo-700 focus:outline-none focus:ring ${
loading && "cursor-not-allowed opacity-35 "
}`}
disabled={loading}
onClick={downloadMindmapSVG}
>
Download transcript. π₯
</button>
<CameraOrbit />
</div>
</div>
</div>
<div className="flex flex-col justify-between lg:col-span-1 col-span-2 overflow-auto">
<h1 className="p-2 text-2xl text-gray-800 font-semibold text-center">
πΊ Chat with the Video πΊ
</h1>
<div className="p-2">
<div className="flex items-center justify-start flex-col max-h-3/5">
<div
ref={endOfMessagesRef}
className=" p-4 flex flex-col m-4 w-full max-h-4/5 border text-xl border-gray-300 rounded-md bg-gray-100"
id="chat-message"
>
{/* <div>
<ReactMarkdown>{"# Markdown"}</ReactMarkdown>
</div> */}
{messages.map((msg, idx) => (
<div
key={idx}
className={` ${
msg.role === "user"
? "text-indigo-600 font-bold mt-3"
: "text-gray-700 "
}`}
ref={idx === messages.length - 1 ? endOfMessagesRef : null}
>
<ReactMarkdown className="markdown">
{msg.content}
</ReactMarkdown>
{/* Show buttopns of 3 timestamps */}
{/* {msg.content} */}
{msg.role === "assistant" && (
<div className="flex space-x-4 mt-2">
{timestamps.map((time, idx) => (
<button
key={idx}
className="bg-indigo-200 hover:bg-indigo-400 text-white py-1 px-3 rounded-lg"
onClick={() => {
if (player) {
player.seekTo(time);
player.pauseVideo();
}
}}
>
{"Ref "}
{idx + 1}
</button>
))}
</div>
)}
</div>
))}
</div>
</div>
</div>
<div
className="p-2 absolute w-full bg-white"
id="chat-input"
style={{ position: "sticky", bottom: 0 }}
>
<div className="flex items-center justify-end w-full space-x-4">
<input
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="π€ Ask me anything! ... "
className="flex-grow w-5/6 px-8 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring focus:border-indigo-500"
/>
{/* {loading && (
<div
style={{ position: "relative", right: "640px", top: "50%" }}
className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-purple-500"
></div>
)} */}
{/* <button
onClick={sendMessage}
className={`px-2.5 py-2.5 bg-indigo-600 text-white rounded-md font-semibold text-lg hover:bg-indigo-700 focus:outline-none focus:ring ${
loading && "cursor-not-allowed opacity-35 "
}`}
disabled={loading}
>
π€Send
</button> */}
<button
onClick={sendMessage}
disabled={loading}
type="button"
className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-2.5 text-center me-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800 inline-flex items-center"
>
{loading && (
<svg
aria-hidden="true"
role="status"
className="inline w-4 h-4 me-3 text-white animate-spin"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="#E5E7EB"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentColor"
/>
</svg>
)}
{loading ? "Loading..." : "π€ Send"}
</button>
</div>
</div>
</div>
</div>
</div>
);
}
export default App;
|