Skip to content

Commit

Permalink
feat: added integration with analysis endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
webtaken committed Nov 26, 2023
1 parent d79e424 commit f1ee6c9
Show file tree
Hide file tree
Showing 8 changed files with 128 additions and 35 deletions.
20 changes: 9 additions & 11 deletions go-server/handlers/youtube.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,16 +263,15 @@ func YoutubeAnalysisHandler(c *fiber.Ctx) error {
}

////////////////////////////////////////////////
fmt.Printf("[YoutubeAnalysisHandler] Number of comments success Bert: %d\n",
log.Printf("[YoutubeAnalysisHandler] Number of comments success Bert: %d\n",
analysis.Results.BertResults.SuccessCount)
fmt.Printf("[YoutubeAnalysisHandler] Number of comments failed Bert: %d\n",
log.Printf("[YoutubeAnalysisHandler] Number of comments failed Bert: %d\n",
analysis.Results.BertResults.ErrorsCount)
fmt.Printf("[YoutubeAnalysisHandler] Number of comments success Roberta: %d\n",
log.Printf("[YoutubeAnalysisHandler] Number of comments success Roberta: %d\n",
analysis.Results.RobertaResults.SuccessCount)
fmt.Printf("[YoutubeAnalysisHandler] Number of comments failed Roberta: %d\n",
log.Printf("[YoutubeAnalysisHandler] Number of comments failed Roberta: %d\n",
analysis.Results.RobertaResults.ErrorsCount)
c.JSON(successResp)
return c.SendStatus(http.StatusOK)
return c.Status(http.StatusOK).JSON(successResp)
}

// This means we have received email hence this video is large so we do all
Expand Down Expand Up @@ -350,7 +349,7 @@ func YoutubeAnalysisHandler(c *fiber.Ctx) error {
analysis.Results.RobertaResults.ErrorsCount)
}(videoData)

return c.SendStatus(http.StatusOK)
return c.Status(http.StatusOK).JSON(fiber.Map{})
}

// @Summary Simple analysis with BERT model for the landing page
Expand Down Expand Up @@ -409,9 +408,8 @@ func YoutubeAnalysisLandingHandler(c *fiber.Ctx) error {
CreatedAt: time.Now().UTC(),
}

fmt.Printf("[YoutubeAnalysisLandingHandler] Number of comments success Bert: %d\n", results.BertResults.SuccessCount)
fmt.Printf("[YoutubeAnalysisLandingHandler] Number of comments failed Bert: %d\n", results.BertResults.ErrorsCount)
c.JSON(successResp)
log.Printf("[YoutubeAnalysisLandingHandler] Number of comments success Bert: %d\n", results.BertResults.SuccessCount)
log.Printf("[YoutubeAnalysisLandingHandler] Number of comments failed Bert: %d\n", results.BertResults.ErrorsCount)

return c.SendStatus(http.StatusOK)
return c.Status(http.StatusOK).JSON(successResp)
}
25 changes: 21 additions & 4 deletions gptube/components/dashboard/button-new-analysis.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,31 @@ import { useVideoPreview } from '@/hooks/use-video-preview'
import { isValidEmail, isValidYoutubeUrl } from '@/utils/validations.utils'
import { useForm } from '@/hooks/use-form'
import { useAuth } from '@/hooks/use-auth'
import { extractYTVideoID } from '@/utils'
import { useDashboardAnalysis } from '@/hooks/use-dashboard-analysis'

import { Button } from '../Common/button'

import { VideoPreview } from './video-preview'

export function ButtonNewAnalysis() {
const { user } = useAuth()
const { handleChange, email, showEmail, url } = useForm({
let { handleChange, email, showEmail, url } = useForm({
url: '',
email: user?.email || '',
showEmail: true,
showEmail: false,
})

const { handleAnalysis, isLoading, dataAnalysis } = useDashboardAnalysis()

const [debouncedUrl] = useDebounce(url, 500)
const modalAnalysis = useDisclosure()
const videoPreviewQuery = useVideoPreview(debouncedUrl)

const isInvalidUrl = !isValidYoutubeUrl(url)
const isInvalidEmail = email === '' || !isValidEmail(email)
const isInvalid = isInvalidUrl || (showEmail && isInvalidEmail)
const videoId = extractYTVideoID(debouncedUrl) || ''

return (
<>
Expand Down Expand Up @@ -122,9 +128,20 @@ export function ButtonNewAnalysis() {
videoPreviewQuery.isSuccess ? 'hover:!bg-opacity-60' : ''
} font-medium text-white disabled:cursor-not-allowed transition-opacity`}
color="success"
disabled={isInvalidUrl || isInvalidEmail || url.length === 0}
isDisabled={isInvalid}
isLoading={isLoading}
radius="sm"
onPress={onClose}
onPress={async () => {
if (!showEmail) {
email = ''
await handleAnalysis('1', videoId, email)
onClose()

return
}
handleAnalysis('1', videoId, email)
onClose()
}}
>
Start analysis
</Button>
Expand Down
5 changes: 2 additions & 3 deletions gptube/components/videos/MainStatistics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ export function MainStatistics({ results, isLoading }: MainStatisticsProps) {
<p className="py-4 text-base">
This recommendation is based on the most negative comments you received in your video.
Such comments may stem from discomfort with the discussed topic, disagreement with your
views, or simply the presence of detractors. Take it just as a recommendation, we
don&apos;t have the truth maybe your channel treats controversial topics so don&apos;t
take it to seriously 😉.
views, or simply the presence of detractors. We don&apos;t have the truth maybe your
channel treats controversial topics so don&apos;t take it to seriously 😉.
</p>
<section>
<p className="h-56 py-2 pl-3 overflow-auto text-sm whitespace-pre-line rounded-lg bg-slate-50">
Expand Down
2 changes: 1 addition & 1 deletion gptube/constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const KEY_ANALYSIS_LANDING = 'gptube-analysis'
export const KEY_ANALYSIS_LANDING = 'gptube-analysis'
2 changes: 2 additions & 0 deletions gptube/constants/general.constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export const DEFAULT_PAGE_PAGINATION = 1

export const DEFAULT_PAGE_SIZE_PAGINATION = 10

export const CONTACT_SUPPORT_X = '@node_srojas1'
77 changes: 77 additions & 0 deletions gptube/hooks/use-dashboard-analysis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import type { ModelsYoutubeAnalyzerReqBody } from "@/gptube-api";
import type { FormEvent } from "react";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import toast from "react-hot-toast";

import { apiClient } from "@/gptube-api";
import { getAnalysisLandingFromCache } from "@/services/get-analysis-landing-from-cache.service";
import { extractYTVideoID } from "@/utils";

import { videoQueryKeys } from "./video-query-keys";
import {
DEFAULT_PAGE_PAGINATION,
DEFAULT_PAGE_SIZE_PAGINATION,
CONTACT_SUPPORT_X,
} from "@/constants/general.constants";

export function useDashboardAnalysis() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: (data: ModelsYoutubeAnalyzerReqBody) => {
if (!data.email || data.email === "") {
toast.success("Analysis started, please wait...");
} else {
toast.success("Analysis started, the results will be sent to your email.");
}
return apiClient.apiYoutubeAnalysisPost({
video: data,
});
},
onSuccess: (data) => {
queryClient.invalidateQueries(
videoQueryKeys.videosAnalyzed({
// TODO: implement authentication
userId: "1",
page: DEFAULT_PAGE_PAGINATION,
pageSize: DEFAULT_PAGE_SIZE_PAGINATION,
}),
{ exact: true },
);
queryClient.setQueryData(videoQueryKeys.videoAnalysis(data.videoId || ""), data);
},
onError: (error) => {
if (error instanceof Error) {
toast.error(error.message);
return;
}
toast.error(
`Something went wrong. Please try again later or contact ${CONTACT_SUPPORT_X} on X.`,
);
},
});

const handleAnalysis = async (userId: string, videoId: string, email?: string) => {
const data: ModelsYoutubeAnalyzerReqBody = {
userId: userId,
videoId: videoId,
};
if (email && email !== "") {
data["email"] = email;
}
await mutation.mutateAsync(data);
};

useEffect(() => {
if (mutation.error instanceof Error) {
toast.error(mutation.error.message);
}
}, [mutation.error, mutation.isError]);

return {
handleAnalysis,
isLoading: mutation.isLoading,
dataAnalysis: mutation.data,
};
}
21 changes: 11 additions & 10 deletions gptube/hooks/video-query-keys.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
export const videoQueryKeys = {
videoPreview: (videoURL: string) => ['video-preview', videoURL] as const,
videoPreview: (videoURL: string) => ["video-preview", videoURL] as const,
videoAnalysis: (videoId: string) => ["video-analysis", videoId] as const,
videosAnalyzed: (args: { userId: string; page: number; pageSize: number }) =>
['videos-analyzed', { ...args }] as const,
videoStats: (args: { userId: string; videoId: string }) => ['video-stats', { ...args }] as const,
["videos-analyzed", { ...args }] as const,
videoStats: (args: { userId: string; videoId: string }) => ["video-stats", { ...args }] as const,
videoNegativeComments: (args: {
userId: string
videoId: string
page: number
pageSize: number
}) => ['video-negative-comments', { ...args }] as const,
videoLanding: () => ['video-landing'] as const,
}
userId: string;
videoId: string;
page: number;
pageSize: number;
}) => ["video-negative-comments", { ...args }] as const,
videoLanding: () => ["video-landing"] as const,
};
11 changes: 5 additions & 6 deletions gptube/utils/validations.utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { YOUTUBE_URL_REGEX } from '@/constants/youtube.constants'
import { YOUTUBE_URL_REGEX } from "@/constants/youtube.constants";

const EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i
const EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i;

export function isValidYoutubeUrl(url: string) {
if (url.length === 0) return true

return url.match(YOUTUBE_URL_REGEX) !== null
if (url.length === 0) return false;
return url.match(YOUTUBE_URL_REGEX) !== null;
}

export function isValidEmail(email: string) {
return EMAIL_REGEX.exec(email) !== null
return EMAIL_REGEX.exec(email) !== null;
}

0 comments on commit f1ee6c9

Please sign in to comment.