Spaces:
Sleeping
Sleeping
File size: 5,133 Bytes
e4c7604 | 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 | import { GoogleGenAI } from "@google/genai";
export interface ChatHistoryItem {
role: 'user' | 'model';
parts: { text: string }[];
}
export class GeminiService {
static getAI() {
// @ts-ignore
let apiKey = (typeof process !== 'undefined' && (process.env?.API_KEY || process.env?.GEMINI_API_KEY)) || import.meta.env.VITE_GEMINI_API_KEY || '';
// Fallback for Docker runtime replacement
if (!apiKey || apiKey.includes('__GEMINI_API_KEY__')) {
apiKey = 'AIzaSyAyVva5wY2g6kmoG3bafrwf4dzM8xLrqDk'; // Hardcoded fallback as requested for "automatic" setup
}
return new GoogleGenAI({ apiKey });
}
/**
* General Text Chat using Gemini 3 Flash.
* Includes Google Search Grounding for up-to-date info.
*/
static async chat(prompt: string, history: ChatHistoryItem[] = []) {
const ai = this.getAI();
try {
const contents = [
...history,
{ role: 'user', parts: [{ text: prompt }] }
];
const response = await ai.models.generateContent({
model: 'gemini-3-flash-preview',
contents: contents,
config: {
tools: [{ googleSearch: {} }],
temperature: 0.7,
}
});
const text = response.text || "Bhai, model ne koi response nahi diya.";
// Extracting grounding chunks for search transparency
const grounding = response.candidates?.[0]?.groundingMetadata?.groundingChunks?.map((chunk: any) => ({
title: chunk.web?.title || 'Verified Source',
uri: chunk.web?.uri || ''
})).filter((c: any) => c.uri) || [];
return { text, grounding };
} catch (error) {
console.error("Chat Error:", error);
return { text: "Network error! Please check your connection or API key.", grounding: [] };
}
}
/**
* High-Quality Image Generation using Gemini 3 Pro Image.
* Mandates API key selection check as per guidelines.
*/
static async generateImage(prompt: string) {
if (typeof window !== 'undefined' && (window as any).aistudio) {
const hasKey = await (window as any).aistudio.hasSelectedApiKey();
if (!hasKey) {
await (window as any).aistudio.openSelectKey();
}
}
const ai = this.getAI();
try {
const response = await ai.models.generateContent({
model: 'gemini-3-pro-image-preview',
contents: { parts: [{ text: prompt }] },
config: {
imageConfig: {
aspectRatio: "1:1",
imageSize: "1K"
}
}
});
// Find the image part in the parts array
if (response.candidates?.[0]?.content?.parts) {
for (const part of response.candidates[0].content.parts) {
if (part.inlineData) {
return `data:image/png;base64,${part.inlineData.data}`;
}
}
}
throw new Error("No image data in response.");
} catch (error) {
console.error("Image Gen Error:", error);
throw error;
}
}
/**
* Cinematic Video Generation using Veo.
* Includes operation polling and API key attachment to fetch.
*/
static async generateVideo(prompt: string) {
if (typeof window !== 'undefined' && (window as any).aistudio) {
const hasKey = await (window as any).aistudio.hasSelectedApiKey();
if (!hasKey) {
await (window as any).aistudio.openSelectKey();
}
}
const ai = this.getAI();
try {
let operation = await ai.models.generateVideos({
model: 'veo-3.1-fast-generate-preview',
prompt: prompt,
config: {
numberOfVideos: 1,
resolution: '720p',
aspectRatio: '16:9'
}
});
// Poll for completion
while (!operation.done) {
await new Promise(resolve => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({ operation: operation });
}
const downloadLink = operation.response?.generatedVideos?.[0]?.video?.uri;
if (!downloadLink) throw new Error("Video generation failed.");
// Fetch video bytes using the key
// @ts-ignore
const apiKey = ai.apiKey;
const response = await fetch(`${downloadLink}&key=${apiKey}`);
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.error("Video Gen Error:", error);
throw error;
}
}
/**
* Multimodal Vision using Gemini 3 Flash.
*/
static async vision(prompt: string, base64Data: string, mimeType: string) {
const ai = this.getAI();
try {
const response = await ai.models.generateContent({
model: 'gemini-3-flash-preview',
contents: {
parts: [
{ inlineData: { data: base64Data, mimeType: mimeType } },
{ text: prompt }
]
}
});
const text = response.text || "Bhai, model ne image dekh kar koi response nahi diya.";
return { text };
} catch (error) {
console.error("Vision Error:", error);
return { text: "Error analyzing image! Please check your connection." };
}
}
}
|