Skip to content
Snippets Groups Projects
Commit 4553f173 authored by Sukanya K's avatar Sukanya K
Browse files

1st commit

parent 8a6c3f53
No related branches found
No related tags found
No related merge requests found
Showing
with 534 additions and 0 deletions
File added
import requests
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# API Endpoint
url = "https://abg-vision-dev-utech-endpoint-v1-689695695290.asia-south1.run.app/utec/dev/vision/api/v1/generate-image"
# List of preferred languages
languages = ["hi", "as", "gu", "kn", "ml", "mr", "or", "pa", "sd", "ta", "te", "ur"]
# Base payload template
payload_template = {"prompt":"Building service, Color Tone:None, Lighting:None, Composition:None, Content Type:Photo","template_type":"Template 4","category":"water_proofing","preferred_language":"","product":["weather_pro_flex"]}
# Headers
headers = {"Content-Type": "application/json"}
data_list = []
# Loop through each language and make API requests
for lang in languages:
payload = payload_template.copy()
print(payload)
payload["preferred_language"] = lang
response = requests.post(url, json=payload, headers=headers)
print(lang,response)
if response.status_code == 200:
result = response.json()
# Extract image_1 dynamically (if available)
image_url = result[0].get("image_1", "No Image URL") if isinstance(result, list) else "No Image URL"
data_list.append({
"Language": lang,
"Payload": str(payload),
"Response": str(result),
"Image_1": image_url
})
else:
data_list.append({
"Language": lang,
"Payload": str(payload),
"Response": f"Error {response.status_code}",
"Image_1": "N/A"
})
# Convert results to DataFrame
df = pd.DataFrame(data_list)
# Google Sheets Authentication
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("/home/user/Downloads/martech-prod-utech-57484fb42bd9.json", scope)
client = gspread.authorize(creds)
# Open Google Sheet and insert data
SHEET_ID = "1KOToGomUmFWiTDtS3dUAPZzhmk495mH0XAoM4ZMHNno"
spreadsheet = client.open_by_key(SHEET_ID)
worksheet = spreadsheet.sheet1
worksheet.clear()
# Insert headers
worksheet.append_row(["Language", "Payload", "Response", "Image_1"])
# Insert data
for row in data_list:
worksheet.append_row([row["Language"], row["Payload"], row["Response"], row["Image_1"]])
print("Responses saved to Google Sheets")
\ No newline at end of file
import requests
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# API Endpoint
url = "https://abg-vision-dev-abcl-endpoint-v1-1045576192621.asia-south1.run.app/abcl/dev/vision/api/v1/generate-image"
# List of preferred languages
#languages = ["hi", "as", "gu", "kn", "ml", "mr", "or", "pa", "sd", "ta", "te", "ur"]
prompt_1 = [
"Featuring diverse Indian women: entrepreneur, homemaker, professional, and student symbolizing financial independence and homeownership.",
"A young Indian couple seated with a financial advisor, confidently discussing insurance plans.",
"A couple riding bicycles in a scenic park, dressed in white sportswear with red shoes (Hex #C7222A).",
"A couple with their newborn in a warm home setting, expressing joy and security.",
"A couple walking briskly in white sportswear with red shoes, promoting 'Walk towards a healthier you'.",
"A couple jogging in sleek white sportswear with red shoes.",
"A couple jogging in grey sportswear with red shoes.",
"A couple relaxing on the sand post-workout, sipping coconut water in white sportswear with red shoes.",
"Grandmother, mother, and daughter in a cozy home, symbolizing financial stability across generations.",
"A young professional working on a laptop in a co-working space, symbolizing financial independence.",
"A woman proudly standing outside her small business, showcasing success and empowerment.",
"Friends in matching white yoga outfits and red shoes, practicing mindfulness outdoors.",
"A family jogging together in white sportswear with red shoes, promoting a healthy lifestyle.",
"A group of friends cycling through a scenic path in coordinated grey and white sportswear with red shoes.",
"A couple holding keys to their new home, smiling proudly at the doorstep.",
"Parents helping their child study at home, symbolizing investment in education and security.",
"A retired couple enjoying tea on their balcony, symbolizing peace of mind through careful planning."
]
# Base payload template
payload_template = {
"aspect_ratio":"1:1",
"social_media":"Instagram",
"prompt":"",
"category":"photography",
"preferred_language":"en"
}
# Headers
headers = {"Content-Type": "application/json"}
data_list = []
# Google Sheets Authentication
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("/home/user/Downloads/martech-prod-utech-57484fb42bd9.json", scope)
client = gspread.authorize(creds)
# Open Google Sheet and insert data
SHEET_ID = "1GyvYlfb95ECW2GUVHEYVW_0l6bLd3KFQizr2CdWoiis"
spreadsheet = client.open_by_key(SHEET_ID)
worksheet = spreadsheet.sheet1
worksheet.clear()
# Insert headers
worksheet.append_row(["Language", "Payload", "Response", "Image_1", "Image_raw_1", "Image_2", "Image_raw_2", "Image_3", "Image_raw_3"])
# Loop through each language and make API requests
for lang in prompt_1:
payload = payload_template.copy()
print(payload)
payload["prompt"] = lang
response = requests.post(url, json=payload, headers=headers)
print(lang,response)
if response.status_code == 200:
result = response.json()
# Extract image_1 dynamically (if available)
image_url = result[0].get("image_1", "No Image URL") if isinstance(result, list) else "No Image URL"
image_url_raw = result[0].get("image_raw_1", "No Image URL") if isinstance(result, list) else "No Image URL"
image_url1 = result[1].get("image_2", "No Image URL") if isinstance(result, list) else "No Image URL"
image_url_raw1 = result[1].get("image_raw_2", "No Image URL") if isinstance(result, list) else "No Image URL"
image_url2 = result[2].get("image_3", "No Image URL") if isinstance(result, list) else "No Image URL"
image_url_raw2 = result[2].get("image_raw_3", "No Image URL") if isinstance(result, list) else "No Image URL"
worksheet.append_row([lang, str(payload), str(result), image_url, image_url_raw, image_url1, image_url_raw1, image_url2, image_url_raw2])
data_list.append({
"Language": lang,
"Payload": str(payload),
"Response": str(result),
"Image_1": image_url,
"Image_raw_1": image_url_raw,
"Image_2": image_url1,
"Image_raw_2": image_url_raw1,
"Image_3": image_url2,
"Image_raw_3": image_url_raw2
})
else:
data_list.append({
"Language": lang,
"Payload": str(payload),
"Response": f"Error {response.status_code}",
"Image_1": "N/A",
"Image_raw_1": "N/A"
})
# Convert results to DataFrame
df = pd.DataFrame(data_list)
# Insert data
print("Responses saved to Google Sheets")
\ No newline at end of file
File added
import requests
import openpyxl
import json
import sys
import os
# Ensure script can find config module
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Import config variables
from config.config import API_URL_ABHFL, JSON_FOLDER, THEMES_FILE, REPEAT_COUNT
# Ensure themes file exists
if not os.path.exists(THEMES_FILE):
raise FileNotFoundError(f"Error: Themes file '{THEMES_FILE}' not found.")
# Load themes from JSON file
try:
with open(THEMES_FILE, "r", encoding="utf-8") as file:
themes = json.load(file)
if not themes: # Check if file is empty
raise ValueError("Themes file is empty. Please add themes to data.json")
except json.JSONDecodeError as e:
raise ValueError(f"Error decoding JSON: {e}")
print(f" Loaded {len(themes)} themes from '{THEMES_FILE}'\n")
# Create an Excel workbook
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["Theme", "Result 1", "Result 2", "Result 3"]) # Headers
# Iterate through themes and send API requests
for theme_index, theme in enumerate(themes, start=1):
print(f" Processing Theme {theme_index}/{len(themes)}: '{theme}'")
row = [theme] # Store theme in the first column
for i in range(REPEAT_COUNT):
print(f" API Call {i + 1}/{REPEAT_COUNT} for theme: '{theme}'")
payload = {
"preferred_language": "en",
"social_media": "Instagram",
"Char": 500,
"age": ["20-50"],
"gender": "Both",
"theme": theme
}
try:
response = requests.post(API_URL_ABHFL, json=payload)
response.raise_for_status() # Handle HTTP errors
# Parse response
if response.headers.get('Content-Type') == 'application/json':
result = response.json()
print(f" API Response: {result}")
else:
result = "Invalid JSON response"
print(" Invalid JSON response received.")
# Convert result to string for Excel
if isinstance(result, dict):
result = json.dumps(result, ensure_ascii=False)
# Handle Excel cell character limit
if len(result) > 32767:
result = result[:32750] + "..."
print(" Response truncated to fit Excel cell limit.")
row.append(result)
except requests.exceptions.RequestException as e:
error_msg = f"Error: {e}"
row.append(error_msg)
print(f" API call failed: {e}")
print(f" Final row data: {row}\n")
ws.append(row) # Append row after 3 API calls
# Save the Excel file
excel_path = os.path.join(JSON_FOLDER, "Cincin_instagram1.xlsx")
wb.save(excel_path)
print(f"\n Excel file saved successfully at: {excel_path}")
import requests
from langdetect import detect
from googletrans import Translator
from fuzzywuzzy import fuzz
# API URL
API_URL = "https://abg-backend-dev-indriya-endpoint-v1-700549619509.asia-south1.run.app/indriya/dev/backend/api/v1/generate-whatsapp/"
# Function to call the API and get response
def get_api_response(theme, preferred_language):
payload = {"theme": theme, "preferred_language": preferred_language}
headers = {"Content-Type": "application/json"}
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
return response.json().get("generated_whatsapp", "") # Extract message
else:
print(f"API Error: {response.status_code}")
return None
# Function to check translation correctness
def check_translation(api_response, expected_english_text):
detected_lang = detect(api_response) # Detect language of API response
print(f"Detected Language: {detected_lang}")
translator = Translator()
translated_text = translator.translate(api_response, dest="en").text # Translate to English
print(f"Translated Text: {translated_text}")
similarity_score = fuzz.ratio(translated_text.lower(), expected_english_text.lower()) # Compare similarity
print(f"Similarity Score: {similarity_score}%")
return similarity_score
# Example usage
theme = "Joyful Festive Gatherings by Indriya"
preferred_language = "ml" # Change dynamically based on need
expected_english_text = "Indriya’s festive collection is designed to add timeless elegance to your gatherings. We use BIS hallmarked gold and certified natural diamonds in all our jewelry, ensuring the highest quality and authenticity. Each piece is meticulously crafted to reflect the essence of Indian tradition and craftsmanship. Explore our exclusive collection featuring the finest earrings, rings, necklaces, and more for your joyous occasions."
response_text = get_api_response(theme, preferred_language)
if response_text:
similarity_score = check_translation(response_text, expected_english_text)
if similarity_score > 80:
print("✅ Translation is accurate.")
else:
print("❌ Translation might be incorrect. Needs review.")
else:
print("Failed to get API response.")
import requests
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# API Endpoint
url = "https://abg-vision-dev-utech-endpoint-v1-689695695290.asia-south1.run.app/utec/dev/vision/api/v1/generate-image"
# List of preferred languages
languages = ["hi", "as", "gu", "kn", "ml", "mr", "or", "pa", "sd", "ta", "te", "ur"]
# Base payload template
payload_template = {"prompt":"Building service, Color Tone:None, Lighting:None, Composition:None, Content Type:Photo","template_type":"Template 2","category":"water_proofing","preferred_language":"","product":["weather_pro_flex"]}
# Headers
headers = {"Content-Type": "application/json"}
data_list = []
# Google Sheets Authentication
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("/home/user/Downloads/martech-prod-utech-57484fb42bd9.json", scope)
client = gspread.authorize(creds)
# Open Google Sheet and insert data
SHEET_ID = "1GyvYlfb95ECW2GUVHEYVW_0l6bLd3KFQizr2CdWoiis"
spreadsheet = client.open_by_key(SHEET_ID)
worksheet = spreadsheet.sheet1
worksheet.clear()
# Insert headers
worksheet.append_row(["Language", "Payload", "Response", "Image_1"])
# Loop through each language and make API requests
for lang in languages:
payload = payload_template.copy()
print(payload)
payload["preferred_language"] = lang
response = requests.post(url, json=payload, headers=headers)
print(lang,response)
if response.status_code == 200:
result = response.json()
# Extract image_1 dynamically (if available)
image_url = result[0].get("image_1", "No Image URL") if isinstance(result, list) else "No Image URL"
worksheet.append_row([lang, str(payload), str(result), image_url])
data_list.append({
"Language": lang,
"Payload": str(payload),
"Response": str(result),
"Image_1": image_url
})
else:
data_list.append({
"Language": lang,
"Payload": str(payload),
"Response": f"Error {response.status_code}",
"Image_1": "N/A"
})
# Convert results to DataFrame
df = pd.DataFrame(data_list)
# Insert data
print("Responses saved to Google Sheets")
\ No newline at end of file
import gspread
import pandas as pd
from oauth2client.service_account import ServiceAccountCredentials
# Path to your service account key file
SERVICE_ACCOUNT_FILE = "/home/user/Downloads/martech-prod-utech-57484fb42bd9.json"
# Define scope
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
# Authenticate using service account
creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_FILE, scope)
gc = gspread.authorize(creds)
# Open the Google Sheet
SHEET_ID = "1GyvYlfb95ECW2GUVHEYVW_0l6bLd3KFQizr2CdWoiis"
sheet = gc.open_by_key(SHEET_ID)
worksheet = sheet.sheet1 # First worksheet
# Get all data
data = worksheet.get_all_records()
df = pd.DataFrame(data)
# Append a new row
worksheet.append_row(["New Data", 123, "More Data"])
print(df)
\ No newline at end of file
import requests
import openpyxl
import json
import sys
import os
# Ensure script can find config module
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Import config variables
from config.config import API_URL_ABHFL_Blog, JSON_FOLDER, THEMES_FILE, REPEAT_COUNT
# Ensure themes file exists
if not os.path.exists(THEMES_FILE):
raise FileNotFoundError(f"Error: Themes file '{THEMES_FILE}' not found.")
# Load themes from JSON file
try:
with open(THEMES_FILE, "r", encoding="utf-8") as file:
themes = json.load(file)
if not themes: # Check if file is empty
raise ValueError("Themes file is empty. Please add themes to data.json")
except json.JSONDecodeError as e:
raise ValueError(f"Error decoding JSON: {e}")
print(f" Loaded {len(themes)} themes from '{THEMES_FILE}'\n")
# Create an Excel workbook
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["Theme", "Result 1", "Result 2", "Result 3"]) # Headers
# Iterate through themes and send API requests
for theme_index, theme in enumerate(themes, start=1):
print(f" Processing Theme {theme_index}/{len(themes)}: '{theme}'")
row = [theme] # Store theme in the first column
for i in range(REPEAT_COUNT):
print(f" API Call {i + 1}/{REPEAT_COUNT} for theme: '{theme}'")
payload = {
"preferred_language": "en",
"theme": theme
}
try:
response = requests.post(API_URL_ABHFL_Blog, json=payload)
response.raise_for_status() # Handle HTTP errors
# Parse response
if response.headers.get('Content-Type') == 'application/json':
result = response.json()
print(f" API Response: {result}")
else:
result = "Invalid JSON response"
print(" Invalid JSON response received.")
# Convert result to string for Excel
if isinstance(result, dict):
result = json.dumps(result, ensure_ascii=False)
# Handle Excel cell character limit
if len(result) > 32767:
result = result[:32750] + "..."
print(" Response truncated to fit Excel cell limit.")
row.append(result)
except requests.exceptions.RequestException as e:
error_msg = f"Error: {e}"
row.append(error_msg)
print(f" API call failed: {e}")
print(f" Final row data: {row}\n")
ws.append(row) # Append row after 3 API calls
# Save the Excel file
excel_path = os.path.join(JSON_FOLDER, "Cincin_instagram1.xlsx")
wb.save(excel_path)
print(f"\n Excel file saved successfully at: {excel_path}")
File added
File added
import os
import json
# API URL
API_URL_ABHI = "https://abg-martech-backend-services-abhi-dev-685957259135.asia-south1.run.app/abhi/dev/backend/api/v1/generate-ad"
API_URL_ABHFL = "https://abg-backend-dev-abhfl-endpoint-v1-352480358504.asia-south1.run.app/abhfl/dev/backend/api/v1/generate-ad"
API_URL_ABHFL_Blog = "https://abg-backend-dev-abhfl-endpoint-v1-352480358504.asia-south1.run.app/abhfl/dev/backend/api/v1/generate-blogpost"
# Define base directory
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Define correct JSON folder path
JSON_FOLDER = os.path.join(BASE_DIR, "data")
os.makedirs(JSON_FOLDER, exist_ok=True) # Ensure folder exists
# Define correct themes file path
THEMES_FILE = os.path.join(JSON_FOLDER, "ABHFLthemes.json")
# Number of API calls per theme
REPEAT_COUNT = 3
# Ensure themes file exists and is valid JSON
if not os.path.exists(THEMES_FILE):
with open(THEMES_FILE, "w", encoding="utf-8") as file:
json.dump([], file) # Create an empty JSON array
print(f"Config Loaded: \nAPI_URL: {API_URL_ABHFL_Blog}\nJSON_FOLDER: {JSON_FOLDER}\nTHEMES_FILE: {THEMES_FILE}")
[ "Own your dream home with easy home loans", "Buy your perfect home, whether new or resale", "Build your dream home with flexible construction loans", "Upgrade your living space with home improvement loans", "Expand your home with hassle-free extension loans", "Secure the perfect plot for your future home", "Save more with balance transfer and lower interest rates", "Unlock your property’s value with a loan against property", "Affordable housing solutions for every family", "Build smarter with MicroCF construction loans", "Step into your first home with StepUp Home Loan", "Enjoy competitive rates and flexible repayment options", "Quick and simple loans with minimal paperwork", "Experience transparent loans with no hidden charges", "Get personalized support for your home loan journey" ]
\ No newline at end of file
File added
File added
[
"Creamy and elastic, this southern Italian cheese is made from buffalo's milk using the pasta filata method, known as Mozzarella.",
"Creamier and more flavorful than cow's milk mozzarella, this water buffalo cheese offers a unique tanginess, called Bufala Mozzarella.",
"A semi-soft cow's milk cheese from Australia, known for its smooth texture and excellent melting qualities, perfect for pizzas, called Fior Di Latte.",
"A fresh cheese with a thin mozzarella shell filled with a soft mixture of curd and cream, delivering a rich and buttery experience, known as Burrata.",
"A hard, sheep's milk cheese with a sharp and salty flavor, ideal for grating over pasta and casseroles, called Pecorino Romano."
]
{
"prompt": "Building service, Color Tone:None, Lighting:None, Composition:None, Content Type:Photo",
"template_type": "Template 5",
"category": "water_proofing",
"preferred_language": "",
"product": ["weather_pro_flex"]
}
{"prompt":"Building service, Color Tone:None, Lighting:None, Composition:None, Content Type:Photo","template_type":"Template 4","category":"water_proofing","preferred_language":"en","product":["seal_dry_sbr"]}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment