Skip to content

Commit 454829d

Browse files
authored
Merge pull request #26 from GYFX35/feature/google-cloud-integration
Integrate Google Cloud AI services
2 parents 31df5b8 + 8e66f1b commit 454829d

File tree

3 files changed

+159
-18
lines changed

3 files changed

+159
-18
lines changed

app.py

Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import sys
12
import os
3+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
import time
35
import requests
46
import httpx
@@ -15,6 +17,7 @@
1517
from facebook_business.api import FacebookAdsApi
1618
from facebook_business.adobjects.adaccount import AdAccount
1719
from facebook_business.exceptions import FacebookRequestError
20+
import google_ai
1821

1922
load_dotenv(dotenv_path=".env")
2023

@@ -66,8 +69,24 @@ def __repr__(self):
6669
db.init_app(app)
6770
stripe.api_key = os.environ.get("STRIPE_SECRET_KEY")
6871

72+
# --- Meta/Facebook Business SDK Integration ---
73+
def initialize_meta_sdk():
74+
"""Initializes the Meta Business SDK."""
75+
meta_app_id = os.environ.get('META_APP_ID')
76+
meta_app_secret = os.environ.get('META_APP_SECRET')
77+
meta_access_token = os.environ.get('META_ACCESS_TOKEN')
78+
if all([meta_app_id, meta_app_secret, meta_access_token]):
79+
try:
80+
FacebookAdsApi.init(app_id=meta_app_id, app_secret=meta_app_secret, access_token=meta_access_token)
81+
print("Meta Business SDK initialized successfully.")
82+
except Exception as e:
83+
print(f"Error initializing Meta Business SDK: {e}")
84+
else:
85+
print("Meta Business SDK credentials not found in environment variables. Skipping initialization.")
86+
6987
with app.app_context():
7088
initialize_meta_sdk()
89+
google_ai.init_vertexai()
7190

7291
def get_locale():
7392
if 'language' in session:
@@ -614,7 +633,18 @@ def develop_website_endpoint():
614633
prompt = data.get('prompt')
615634
if not prompt:
616635
return jsonify({"error": _("Prompt is required")}), 400
617-
message = generate_website(prompt)
636+
html, css = google_ai.generate_website(prompt)
637+
message = f"""
638+
{_("Here is the generated code for your website.")}
639+
**index.html:**
640+
```html
641+
{html.strip()}
642+
```
643+
**style.css:**
644+
```css
645+
{css.strip()}
646+
```
647+
"""
618648
return jsonify({"status": "success", "message": message})
619649

620650
@app.route('/api/v1/develop/game', methods=['POST'])
@@ -654,7 +684,18 @@ def debug_endpoint():
654684
prompt = data.get('prompt')
655685
if not prompt:
656686
return jsonify({"error": _("Prompt is required")}), 400
657-
message = debug_code(prompt)
687+
688+
# Simple language detection
689+
language = 'html'
690+
if prompt.strip().startswith('{') or '{' in prompt and '}' in prompt:
691+
language = 'css'
692+
693+
errors = google_ai.debug_code(prompt, language)
694+
if not errors:
695+
message = _("No obvious issues found in your %(lang)s code.", lang=language)
696+
else:
697+
message = _("Found potential issues in your %(lang)s code:\n", lang=language) + "\n".join(f"- {error}" for error in errors)
698+
658699
return jsonify({"status": "success", "message": message})
659700

660701
@app.route('/api/v1/market/post', methods=['POST'])
@@ -664,7 +705,7 @@ def market_post_endpoint():
664705
prompt = data.get('prompt')
665706
if not prompt:
666707
return jsonify({"error": _("Prompt is required")}), 400
667-
message = generate_social_media_post(prompt)
708+
message = google_ai.generate_social_media_post(prompt)
668709
return jsonify({"status": "success", "message": message})
669710

670711
@app.route('/api/v1/optimize/ads', methods=['POST'])
@@ -855,21 +896,6 @@ def payment_webhook():
855896
return jsonify(status='success')
856897

857898

858-
# --- Meta/Facebook Business SDK Integration ---
859-
def initialize_meta_sdk():
860-
"""Initializes the Meta Business SDK."""
861-
meta_app_id = os.environ.get('META_APP_ID')
862-
meta_app_secret = os.environ.get('META_APP_SECRET')
863-
meta_access_token = os.environ.get('META_ACCESS_TOKEN')
864-
if all([meta_app_id, meta_app_secret, meta_access_token]):
865-
try:
866-
FacebookAdsApi.init(app_id=meta_app_id, app_secret=meta_app_secret, access_token=meta_access_token)
867-
print("Meta Business SDK initialized successfully.")
868-
except Exception as e:
869-
print(f"Error initializing Meta Business SDK: {e}")
870-
else:
871-
print("Meta Business SDK credentials not found in environment variables. Skipping initialization.")
872-
873899
@app.route('/api/v1/meta/campaigns', methods=['GET'])
874900
@require_api_key
875901
def get_meta_campaigns():

google_ai.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import os
2+
import re
3+
import vertexai
4+
from vertexai.generative_models import GenerativeModel
5+
6+
def init_vertexai():
7+
"""Initializes the Vertex AI SDK."""
8+
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
9+
location = os.environ.get("GOOGLE_CLOUD_LOCATION")
10+
11+
if not all([project_id, location]):
12+
print("Google Cloud project ID and location not found in environment variables. Skipping Vertex AI initialization.")
13+
return
14+
15+
vertexai.init(project=project_id, location=location)
16+
print("Vertex AI SDK initialized successfully.")
17+
18+
def generate_website(prompt: str) -> tuple[str, str]:
19+
"""
20+
Generates HTML and CSS code from a natural language prompt using Vertex AI.
21+
"""
22+
model = GenerativeModel("gemini-1.5-flash")
23+
24+
generation_prompt = f"""
25+
You are a skilled web developer. Your task is to generate the HTML and CSS for a single-page website based on the following user prompt.
26+
27+
User Prompt:
28+
---
29+
{prompt}
30+
---
31+
32+
Your response must be in the following format, with no other text or explanations:
33+
34+
[HTML]
35+
<!DOCTYPE html>
36+
...
37+
</html>
38+
[/HTML]
39+
40+
[CSS]
41+
body {{
42+
...
43+
}}
44+
[/CSS]
45+
"""
46+
47+
try:
48+
response = model.generate_content(generation_prompt)
49+
text_response = response.text
50+
51+
html_match = re.search(r'\[HTML\](.*?)\[/HTML\]', text_response, re.DOTALL)
52+
css_match = re.search(r'\[CSS\](.*?)\[/CSS\]', text_response, re.DOTALL)
53+
54+
html_code = html_match.group(1).strip() if html_match else "<!-- Error: Could not generate HTML. -->"
55+
css_code = css_match.group(1).strip() if css_match else "/* Error: Could not generate CSS. */"
56+
57+
return html_code, css_code
58+
59+
except Exception as e:
60+
print(f"Error generating website with Vertex AI: {e}")
61+
return f"<!-- Error: {e} -->", f"/* Error: {e} */"
62+
63+
def debug_code(code: str, language: str) -> list[str]:
64+
"""
65+
Analyzes code and finds potential issues using Vertex AI.
66+
"""
67+
model = GenerativeModel("gemini-1.5-flash")
68+
69+
generation_prompt = f"""
70+
You are an expert code reviewer. Your task is to analyze the following {language} code and identify any potential bugs, errors, or style issues.
71+
72+
Code:
73+
---
74+
{code}
75+
---
76+
77+
Please list the issues you find, one per line. If you find no issues, return an empty response.
78+
"""
79+
80+
try:
81+
response = model.generate_content(generation_prompt)
82+
errors = response.text.strip().split('\n')
83+
# Filter out empty strings that may result from the split
84+
return [error for error in errors if error]
85+
86+
except Exception as e:
87+
print(f"Error debugging code with Vertex AI: {e}")
88+
return [f"Error: {e}"]
89+
90+
def generate_social_media_post(description: str) -> str:
91+
"""
92+
Generates a social media post from a description using Vertex AI.
93+
"""
94+
model = GenerativeModel("gemini-1.5-flash")
95+
96+
generation_prompt = f"""
97+
You are a creative marketing assistant. Your task is to write an engaging social media post based on the following description.
98+
99+
Description:
100+
---
101+
{description}
102+
---
103+
104+
The post should be short, catchy, and include relevant hashtags.
105+
"""
106+
107+
try:
108+
response = model.generate_content(generation_prompt)
109+
return response.text.strip()
110+
111+
except Exception as e:
112+
print(f"Error generating social media post with Vertex AI: {e}")
113+
return f"Error: {e}"

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,5 @@ anyio
1010
sniffio
1111
stripe
1212
facebook-business
13+
google-cloud-aiplatform
14+
google-auth

0 commit comments

Comments
 (0)