Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import os
|
3 |
+
import mimetypes
|
4 |
+
from google import genai
|
5 |
+
from google.genai import types
|
6 |
+
|
7 |
+
|
8 |
+
def save_binary_file(file_name, data):
|
9 |
+
f = open(file_name, "wb")
|
10 |
+
f.write(data)
|
11 |
+
f.close()
|
12 |
+
|
13 |
+
|
14 |
+
def generate():
|
15 |
+
client = genai.Client(
|
16 |
+
api_key=os.environ.get("GEMINI_API_KEY"),
|
17 |
+
)
|
18 |
+
|
19 |
+
model = "gemini-2.0-flash-exp-image-generation"
|
20 |
+
contents = [
|
21 |
+
types.Content(
|
22 |
+
role="user",
|
23 |
+
parts=[
|
24 |
+
types.Part.from_text(text="""INSERT_INPUT_HERE"""),
|
25 |
+
],
|
26 |
+
),
|
27 |
+
]
|
28 |
+
generate_content_config = types.GenerateContentConfig(
|
29 |
+
temperature=1,
|
30 |
+
top_p=0.95,
|
31 |
+
top_k=40,
|
32 |
+
max_output_tokens=8192,
|
33 |
+
response_modalities=[
|
34 |
+
"image",
|
35 |
+
"text",
|
36 |
+
],
|
37 |
+
safety_settings=[
|
38 |
+
types.SafetySetting(
|
39 |
+
category="HARM_CATEGORY_CIVIC_INTEGRITY",
|
40 |
+
threshold="OFF", # Off
|
41 |
+
),
|
42 |
+
],
|
43 |
+
response_mime_type="text/plain",
|
44 |
+
)
|
45 |
+
|
46 |
+
for chunk in client.models.generate_content_stream(
|
47 |
+
model=model,
|
48 |
+
contents=contents,
|
49 |
+
config=generate_content_config,
|
50 |
+
):
|
51 |
+
if not chunk.candidates or not chunk.candidates[0].content or not chunk.candidates[0].content.parts:
|
52 |
+
continue
|
53 |
+
if chunk.candidates[0].content.parts[0].inline_data:
|
54 |
+
file_name = "ENTER_FILE_NAME"
|
55 |
+
inline_data = chunk.candidates[0].content.parts[0].inline_data
|
56 |
+
file_extension = mimetypes.guess_extension(inline_data.mime_type)
|
57 |
+
save_binary_file(
|
58 |
+
f"{file_name}{file_extension}", inline_data.data
|
59 |
+
)
|
60 |
+
print(
|
61 |
+
"File of mime type"
|
62 |
+
f" {inline_data.mime_type} saved"
|
63 |
+
f"to: {file_name}"
|
64 |
+
)
|
65 |
+
else:
|
66 |
+
print(chunk.text)
|
67 |
+
|
68 |
+
if __name__ == "__main__":
|
69 |
+
generate()
|