Spaces:
Running
Running
File size: 1,861 Bytes
29a3b5e |
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 |
import express from "express";
import 'dotenv/config.js'
import { createServer } from "http";
import { Server } from "socket.io";
import { GoogleGenerativeAI } from "@google/generative-ai";
const app = express();
const httpServer = createServer(app);
app.use(express.static('public'));
const io = new Server(httpServer, { /* options */ });
io.on("connection", (socket) => {
socket.on("ask_api", (client_data) => {
console.log(client_data)
console.log("trying to reach api");
asyncAPICall(client_data, socket)
});
});
// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
async function run() {
// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro"});
const prompt = "Write a story about a magic backpack."
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
console.log(text);
}
//run();
function fileToGenerativePart(path, mimeType) {
return {
inlineData: {
data: path,
mimeType
},
};
}
async function asyncAPICall(data, socket) {
try{
// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro-vision"});
const prompt = data[1]
const imageParts = [
fileToGenerativePart(data[0].slice(22), "image/png"),
];
const result = await model.generateContent([prompt, ...imageParts]);
const response = await result.response;
const text = response.text();
socket.emit("api_response", (text))
}
catch(e){
console.log(e)
socket.emit("api_error", ("ERROR ON API SIDE, SORRY..."))
}
}
httpServer.listen(7860);
console.log("App running on http://localhost:7860")
|