utkarsh134 commited on
Commit
87d3aa4
·
verified ·
1 Parent(s): 3a14ff4

Update app/services/logo_service.py

Browse files
Files changed (1) hide show
  1. app/services/logo_service.py +100 -108
app/services/logo_service.py CHANGED
@@ -1,108 +1,100 @@
1
- from google import genai
2
- from google.genai import types
3
- from PIL import Image
4
- from io import BytesIO
5
- import base64
6
- import time
7
- import os
8
- import uuid
9
- from pathlib import Path
10
- from typing import List, Dict, Tuple
11
-
12
- # Create a temporary directory for storing logos
13
- TEMP_LOGO_DIR = Path("temp_logos")
14
- TEMP_LOGO_DIR.mkdir(exist_ok=True)
15
-
16
- def get_logo_prompts(brand_name: str, domain: str) -> List[str]:
17
- return [
18
- f"Design a professional and elegant logo for {brand_name}, specializing in {domain}. Perhaps incorporate a subtle icon or abstract mark with a sophisticated color palette.",
19
- f"Create a creative and unique logo for {brand_name}, focusing on {domain} solutions. Think outside the box with an unexpected symbol or a clever visual metaphor.",
20
- f"Generate a vibrant and playful logo for {brand_name}, within the {domain} sector. Consider using bright colors and friendly shapes.",
21
- f"Create a natural and organic logo for {brand_name}, operating in the {domain} space. Explore earthy tones and flowing lines or leaf-like elements.",
22
- f"Design an abstract and conceptual logo for {brand_name}, related to {domain}. Focus on conveying the essence of the brand through non-literal imagery.",
23
- ]
24
-
25
- def generate_logos_base64(brand_name: str, domain: str, variation_count: int = 5) -> List[Dict]:
26
- """
27
- Generate logos and return them as base64-encoded strings.
28
-
29
- Returns:
30
- A list of dictionaries containing:
31
- - id: A unique ID for the logo
32
- - base64_data: The base64-encoded image data
33
- - format: The image format (e.g., 'png')
34
- """
35
- api_key = os.getenv("GEMINI_API_KEY")
36
- if not api_key:
37
- raise ValueError("GEMINI_API_KEY environment variable not set")
38
-
39
- # Initialize the client
40
- client = genai.Client(api_key=api_key)
41
- prompts = get_logo_prompts(brand_name, domain)[:variation_count]
42
-
43
- # Create a temporary session directory
44
- session_id = str(uuid.uuid4())
45
- session_dir = TEMP_LOGO_DIR / session_id
46
- session_dir.mkdir(exist_ok=True)
47
-
48
- logo_results = []
49
-
50
- try:
51
- for idx, prompt in enumerate(prompts, 1):
52
- try:
53
- response = client.models.generate_content(
54
- model="gemini-2.0-flash-exp-image-generation",
55
- contents=prompt,
56
- config=types.GenerateContentConfig(
57
- response_modalities=['TEXT', 'IMAGE']
58
- )
59
- )
60
-
61
- for part in response.candidates[0].content.parts:
62
- if part.inline_data is not None:
63
- # Process the image
64
- image = Image.open(BytesIO(part.inline_data.data))
65
-
66
- # Save to a temporary file
67
- filename = f"{brand_name.replace(' ', '_')}_{idx}.png"
68
- file_path = session_dir / filename
69
- image.save(file_path)
70
-
71
- # Read the file and convert to base64
72
- with open(file_path, "rb") as image_file:
73
- encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
74
-
75
- # Add to results
76
- logo_results.append({
77
- "id": f"logo_{idx}",
78
- "base64_data": encoded_string,
79
- "format": "png",
80
- "name": filename
81
- })
82
-
83
- time.sleep(1) # Short pause between logo variations
84
-
85
- except Exception as e:
86
- print(f"Error generating logo {idx}: {str(e)}")
87
-
88
- finally:
89
- # Clean up the temporary directory
90
- cleanup_session(session_id)
91
-
92
- return logo_results
93
-
94
- def cleanup_session(session_id: str):
95
- """
96
- Delete the temporary directory for a session.
97
- """
98
- session_dir = TEMP_LOGO_DIR / session_id
99
- if session_dir.exists():
100
- for file in session_dir.iterdir():
101
- try:
102
- file.unlink()
103
- except:
104
- pass # Ignore errors during cleanup
105
- try:
106
- session_dir.rmdir()
107
- except:
108
- pass # Ignore errors during cleanup
 
1
+ from google import genai
2
+ from google.genai import types
3
+ from PIL import Image
4
+ from io import BytesIO
5
+ import base64
6
+ import time
7
+ import os
8
+ import uuid
9
+ from pathlib import Path
10
+ from typing import List, Dict, Tuple
11
+
12
+ TEMP_LOGO_DIR = Path("temp_logos")
13
+ TEMP_LOGO_DIR.mkdir(parents=True, exist_ok=True)
14
+
15
+ def get_logo_prompts(brand_name: str, domain: str) -> List[str]:
16
+ return [
17
+ f"Design a professional and elegant logo for {brand_name}, specializing in {domain}. Perhaps incorporate a subtle icon or abstract mark with a sophisticated color palette.",
18
+ f"Create a creative and unique logo for {brand_name}, focusing on {domain} solutions. Think outside the box with an unexpected symbol or a clever visual metaphor.",
19
+ f"Generate a vibrant and playful logo for {brand_name}, within the {domain} sector. Consider using bright colors and friendly shapes.",
20
+ f"Create a natural and organic logo for {brand_name}, operating in the {domain} space. Explore earthy tones and flowing lines or leaf-like elements.",
21
+ f"Design an abstract and conceptual logo for {brand_name}, related to {domain}. Focus on conveying the essence of the brand through non-literal imagery.",
22
+ ]
23
+
24
+ def generate_logos_base64(brand_name: str, domain: str, variation_count: int = 5) -> List[Dict]:
25
+ """
26
+ Generate logos and return them as base64-encoded strings.
27
+
28
+ Returns:
29
+ A list of dictionaries containing:
30
+ - id: A unique ID for the logo
31
+ - base64_data: The base64-encoded image data
32
+ - format: The image format (e.g., 'png')
33
+ """
34
+ api_key = os.getenv("GEMINI_API_KEY")
35
+ if not api_key:
36
+ raise ValueError("GEMINI_API_KEY environment variable not set")
37
+
38
+ client = genai.Client(api_key=api_key)
39
+ prompts = get_logo_prompts(brand_name, domain)[:variation_count]
40
+
41
+ session_id = str(uuid.uuid4())
42
+ session_dir = TEMP_LOGO_DIR / session_id
43
+ session_dir.mkdir(exist_ok=True)
44
+
45
+ logo_results = []
46
+
47
+ try:
48
+ for idx, prompt in enumerate(prompts, 1):
49
+ try:
50
+ response = client.models.generate_content(
51
+ model="gemini-2.0-flash-exp-image-generation",
52
+ contents=prompt,
53
+ config=types.GenerateContentConfig(
54
+ response_modalities=['TEXT', 'IMAGE']
55
+ )
56
+ )
57
+
58
+ for part in response.candidates[0].content.parts:
59
+ if part.inline_data is not None:
60
+ image = Image.open(BytesIO(part.inline_data.data))
61
+
62
+ filename = f"{brand_name.replace(' ', '_')}_{idx}.png"
63
+ file_path = session_dir / filename
64
+ image.save(file_path)
65
+
66
+ with open(file_path, "rb") as image_file:
67
+ encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
68
+
69
+ logo_results.append({
70
+ "id": f"logo_{idx}",
71
+ "base64_data": encoded_string,
72
+ "format": "png",
73
+ "name": filename
74
+ })
75
+
76
+ time.sleep(1)
77
+
78
+ except Exception as e:
79
+ print(f"Error generating logo {idx}: {str(e)}")
80
+
81
+ finally:
82
+ cleanup_session(session_id)
83
+
84
+ return logo_results
85
+
86
+ def cleanup_session(session_id: str):
87
+ """
88
+ Delete the temporary directory for a session.
89
+ """
90
+ session_dir = TEMP_LOGO_DIR / session_id
91
+ if session_dir.exists():
92
+ for file in session_dir.iterdir():
93
+ try:
94
+ file.unlink()
95
+ except:
96
+ pass
97
+ try:
98
+ session_dir.rmdir()
99
+ except:
100
+ pass