Riddwam commited on
Commit
ef4bb7b
·
verified ·
1 Parent(s): 74bc759

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -127
app.py CHANGED
@@ -1,127 +1,37 @@
1
- # @license
2
- # SPDX-License-Identifier: Apache-2.0
3
-
4
- // Assuming GoogleGenAI is loaded globally from google-genai.js
5
- const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});
6
-
7
- const chat = ai.chats.create({
8
- model: 'gemini-2.0-flash-preview-image-generation',
9
- config: {
10
- responseModalities: [Modality.TEXT, Modality.IMAGE],
11
- },
12
- history: [],
13
- });
14
-
15
- const userInput = document.querySelector('#input');
16
- const modelOutput = document.querySelector('#output');
17
- const slideshow = document.querySelector('#slideshow');
18
- const error = document.querySelector('#error');
19
-
20
- additionalInstructions = """
21
- Use a fun story about lots of tiny cats as a metaphor.
22
- Keep sentences short but conversational, casual, and engaging.
23
- Generate a cute, minimal illustration for each sentence with black ink on white background.
24
- No commentary, just begin your explanation.
25
- Keep going until you're done.
26
- """
27
-
28
- async function addSlide(text, image) {
29
- const slide = document.createElement('div');
30
- slide.className = 'slide';
31
- const caption = document.createElement('div');
32
- caption.innerHTML = await marked.parse(text);
33
- slide.append(image);
34
- slide.append(caption);
35
- slideshow.append(slide);
36
- }
37
-
38
- function parseError(error) {
39
- const regex = /{"error":(.*)}/gm;
40
- const m = regex.exec(error);
41
- try {
42
- const e = m[1];
43
- const err = JSON.parse(e);
44
- return err.message;
45
- } catch (e) {
46
- return error;
47
- }
48
- }
49
-
50
- async function generate(message) {
51
- userInput.disabled = true;
52
-
53
- chat.history.length = 0;
54
- modelOutput.innerHTML = '';
55
- slideshow.innerHTML = '';
56
- error.innerHTML = '';
57
- error.toggleAttribute('hidden', true);
58
-
59
- try {
60
- const userTurn = document.createElement('div');
61
- userTurn.innerHTML = await marked.parse(message);
62
- userTurn.className = 'user-turn';
63
- modelOutput.append(userTurn);
64
- userInput.value = '';
65
-
66
- const result = await chat.sendMessageStream({
67
- message: message + additionalInstructions,
68
- });
69
-
70
- let text = '';
71
- let img = null;
72
-
73
- for await (const chunk of result) {
74
- for (const candidate of chunk.candidates) {
75
- for (const part of candidate.content.parts ?? []) {
76
- if (part.text) {
77
- text += part.text;
78
- } else {
79
- try {
80
- const data = part.inlineData;
81
- if (data) {
82
- img = document.createElement('img');
83
- img.src = `data:image/png;base64,` + data.data;
84
- } else {
85
- console.log('no data', chunk);
86
- }
87
- } catch (e) {
88
- console.log('no data', chunk);
89
- }
90
- }
91
- if (text && img) {
92
- await addSlide(text, img);
93
- slideshow.removeAttribute('hidden');
94
- text = '';
95
- img = null;
96
- }
97
- }
98
- }
99
- }
100
- if (img) {
101
- await addSlide(text, img);
102
- slideshow.removeAttribute('hidden');
103
- text = '';
104
- }
105
- } catch (e) {
106
- const msg = parseError(e);
107
- error.innerHTML = `Something went wrong: ${msg}`;
108
- error.removeAttribute('hidden');
109
- }
110
- userInput.disabled = false;
111
- userInput.focus();
112
- }
113
-
114
- userInput.addEventListener('keydown', async (e) => {
115
- if (e.code === 'Enter') {
116
- e.preventDefault();
117
- const message = userInput.value;
118
- await generate(message);
119
- }
120
- });
121
-
122
- const examples = document.querySelectorAll('#examples li');
123
- examples.forEach((li) =>
124
- li.addEventListener('click', async (e) => {
125
- await generate(li.textContent);
126
- }),
127
- );
 
1
+ from flask import Flask, request, jsonify
2
+ import os
3
+
4
+ # Initialize Flask application
5
+ app = Flask(__name__)
6
+
7
+ # Load API key from environment variable
8
+ API_KEY = os.environ.get('GEMINI_API_KEY')
9
+ if not API_KEY:
10
+ raise ValueError("GEMINI_API_KEY environment variable not set")
11
+
12
+ # Placeholder for AI initialization (replace with actual library if available)
13
+ # For example, this could be a Google Gemini AI client
14
+ class GoogleGenAI:
15
+ def __init__(self, api_key):
16
+ self.api_key = api_key
17
+
18
+ def process_request(self, text):
19
+ # Simulate an AI response (replace with actual API call)
20
+ return f"Processed: {text}"
21
+
22
+ ai = GoogleGenAI(api_key=API_KEY)
23
+
24
+ # Define a simple route
25
+ @app.route('/api/process', methods=['POST'])
26
+ def process_text():
27
+ data = request.get_json()
28
+ if not data or 'text' not in data:
29
+ return jsonify({'error': 'No text provided'}), 400
30
+
31
+ text = data['text']
32
+ result = ai.process_request(text)
33
+ return jsonify({'result': result})
34
+
35
+ # Run the application
36
+ if __name__ == '__main__':
37
+ app.run(host='0.0.0.0', port=5000, debug=True)