Spaces:
Sleeping
Sleeping
Download app.py from elisda/greenplate: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/elisda/greenplate/resolve/main/app.py
- Command line
-
hf download hf://spaces/elisda/greenplate/app.py
-
curl -L -o app.py https://huggingface.co/spaces/elisda/greenplate/resolve/main/app.py
11.5 kB
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| import json | |
| import os | |
| import requests | |
| from pypdf import PdfReader | |
| import gradio as gr | |
| import google.generativeai as genai | |
| from langdetect import detect | |
| import pycountry | |
| import time | |
| from datetime import datetime | |
| from hashlib import md5 | |
| load_dotenv(override=True) | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") | |
| GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") | |
| DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") | |
| openai_model="gpt-4o" | |
| def push(text): | |
| requests.post( | |
| "https://api.pushover.net/1/messages.json", | |
| data={ | |
| "token": os.getenv("PUSHOVER_TOKEN"), | |
| "user": os.getenv("PUSHOVER_USER"), | |
| "message": text, | |
| } | |
| ) | |
| def record_user_details(email, name="Name not provided", notes="not provided"): | |
| push(f"Recording {name} with email {email} and notes {notes}") | |
| return {"recorded": "ok"} | |
| def record_unknown_question(question): | |
| push(f"Recording {question}") | |
| return {"recorded": "ok"} | |
| record_user_details_json = { | |
| "name": "record_user_details", | |
| "description": "Use this tool to record that a user is interested in being in touch and provided an email address", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "email": { | |
| "type": "string", | |
| "description": "The email address of this user" | |
| }, | |
| "name": { | |
| "type": "string", | |
| "description": "The user's name, if they provided it" | |
| } | |
| , | |
| "notes": { | |
| "type": "string", | |
| "description": "Any additional information about the conversation that's worth recording to give context" | |
| } | |
| }, | |
| "required": ["email"], | |
| "additionalProperties": False | |
| } | |
| } | |
| record_unknown_question_json = { | |
| "name": "record_unknown_question", | |
| "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "question": { | |
| "type": "string", | |
| "description": "The question that couldn't be answered" | |
| }, | |
| }, | |
| "required": ["question"], | |
| "additionalProperties": False | |
| } | |
| } | |
| tools = [{"type": "function", "function": record_user_details_json}, | |
| {"type": "function", "function": record_unknown_question_json}] | |
| #genai.configure(api_key=os.getenv(GOOGLE_API_KEY)) | |
| GOOGLE_API_KEY=os.environ["GOOGLE_API_KEY"] | |
| genai.configure(api_key=GOOGLE_API_KEY) | |
| #openai.api_key = OPENAI_API_KEY | |
| #openai_client = OpenAI(api_key=os.getenv(OPENAI_API_KEY)) | |
| OPENAI_API_KEY=os.environ["OPENAI_API_KEY"] | |
| openai_client = OpenAI(api_key=OPENAI_API_KEY) | |
| def translate_text_with_gemini(text, target_language): | |
| prompt = f"""You are a professional translator. Translate the following text to {target_language} without adding, changing, or omitting any details. | |
| Text: | |
| {text} | |
| """ | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| response = model.generate_content(prompt) | |
| return response.text | |
| def detect_language_name(text): | |
| try: | |
| # Detect ISO 639-1 language code | |
| lang_code = detect(text) | |
| # Get full language name using pycountry | |
| language = pycountry.languages.get(alpha_2=lang_code) | |
| if language: | |
| return language.name | |
| else: | |
| return f"Unknown language code: {lang_code}" | |
| except Exception as e: | |
| return f"Error detecting language: {str(e)}" | |
| # Detect language | |
| def detect_language(text): | |
| try: | |
| return detect(text) | |
| except: | |
| return "en" | |
| def translate_with_openai(text, target_lang): | |
| prompt = f"Translate the following to {target_lang}:\n\n{text}" | |
| response = openai_client.chat.completions.create( | |
| model=openai_model, # You can also use "gpt-3.5-turbo" | |
| messages=[ | |
| {"role": "system", "content": "Translate the following exactly and completely"}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| max_tokens=300, | |
| temperature=0.0 | |
| ) | |
| return response.choices[0].message.content.strip() | |
| # Example usage | |
| #translated = translate_with_openai("I worked at Meta Reality Labs and Amazon Lab126 in California.", "Malayalam") | |
| #print("Translated:", translated) | |
| def translate_with_gemini(text, target_lang): | |
| prompt = f"""Translate the following text to {target_lang}. Do not add or change any details. Translate exactly and completely | |
| Text:{text}""" | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| response = model.generate_content(prompt) | |
| return response.text.strip() | |
| # Configuration | |
| openai_client.api_base = "https://openrouter.ai/api/v1" | |
| #openai_client.api_key = os.getenv(DEEPSEEK_API_KEY) | |
| DEEPSEEK_API_KEY=os.environ["DEEPSEEK_API_KEY"] | |
| openai_client.api_key = DEEPSEEK_API_KEY | |
| MODEL_NAME = "deepseek-chat" | |
| # Simple cache dict (in-memory) | |
| translation_cache = {} | |
| def is_off_peak(): | |
| """Returns True if current UTC time is within off-peak hours (16:30–00:30 UTC)""" | |
| now = datetime.utcnow() | |
| hour = now.hour + now.minute / 60 | |
| return 16.5 <= hour < 24.5 | |
| def get_cache_key(text, target_language): | |
| return md5(f"{text}|{target_language}".encode()).hexdigest() | |
| def translate_with_deepseek(text, target_language): | |
| cache_key = get_cache_key(text, target_language) | |
| if cache_key in translation_cache: | |
| return translation_cache[cache_key] | |
| system_prompt = "You are a professional translator. Translate the user's text without altering meaning." | |
| user_prompt = f"Translate to {target_language}:\n{text}" | |
| response = openai_client.ChatCompletion.create( | |
| model=MODEL_NAME, | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt} | |
| ], | |
| temperature=0.2 if is_off_peak() else 0.3 | |
| ) | |
| translated = response["choices"][0]["message"]["content"] | |
| translation_cache[cache_key] = translated | |
| return translated | |
| def evaluate_translations_openai(original_text, openai_translation, gemini_translation, target_lang): | |
| prompt = f"""You are a multilingual evaluator. Compare two translations of the same English text into {target_lang}. | |
| Choose the one that is more accurate, complete, and faithful to the original meaning. | |
| Original text: | |
| {original_text} | |
| Translation A (OpenAI): | |
| {openai_translation} | |
| Translation B (Gemini): | |
| {gemini_translation} | |
| Respond with only the better translation text. Do not mention 'Translation A' or 'Translation B'. Just return the selected translation itself.""" | |
| response = openai_client.chat.completions.create( | |
| model=openai_model, | |
| messages=[ | |
| {"role": "system", "content": "You are a professional translation evaluator."}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| max_tokens=300, | |
| temperature=0.0 | |
| ) | |
| return response.choices[0].message.content.strip() | |
| def get_best_translation(text, target_lang): | |
| #openai_result = translate_with_openai(text, target_lang) | |
| openai_result=translate_with_deepseek(text, target_lang) | |
| gemini_result = translate_with_gemini(text, target_lang) | |
| verdict = evaluate_translations_openai(text, openai_result, gemini_result, target_lang) | |
| return verdict | |
| #return { | |
| # "original": text, | |
| ## "openai_translation": openai_result, | |
| # "gemini_translation": gemini_result, | |
| # "verdict": verdict | |
| #} | |
| #result = get_best_translation("I worked at Meta Reality Labs and Amazon Lab126 in California.","Malayalam") | |
| #print("Best Translation:", result["verdict"]) | |
| class Me: | |
| def __init__(self): | |
| self.openai = OpenAI(api_key=OPENAI_API_KEY) | |
| self.name = "Green Plate Castle Craves" | |
| reader = PdfReader("Menu.pdf") | |
| self.linkedin = "" | |
| for page in reader.pages: | |
| text = page.extract_text() | |
| if text: | |
| self.linkedin += text | |
| with open("summary.txt", "r", encoding="utf-8") as f: | |
| self.summary = f.read() | |
| def handle_tool_call(self, tool_calls): | |
| results = [] | |
| for tool_call in tool_calls: | |
| tool_name = tool_call.function.name | |
| arguments = json.loads(tool_call.function.arguments) | |
| print(f"Tool called: {tool_name}", flush=True) | |
| tool = globals().get(tool_name) | |
| result = tool(**arguments) if tool else {} | |
| results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id}) | |
| return results | |
| def system_prompt(self): | |
| system_prompt = f"You are acting as {self.name}. You are answering questions on {self.name}'s website, \ | |
| particularly questions related to {self.name}'s services, contact etc. \ | |
| Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \ | |
| You are given a summary of {self.name}'s services which you can use to answer limit to stricltly under 300 words for each answer . \ | |
| Be professional and engaging use simple english, as if talking to a potential client who came across the website. \ | |
| Answer should limit to stricltly under 300 words for each answer \ | |
| If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \ | |
| If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. Limit anser within 350 words " | |
| system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## \n\n" | |
| system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}. Limit to stricltly under 300 words for each answer" | |
| return system_prompt | |
| def chat(self, message, history): | |
| messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}] | |
| done = False | |
| while not done: | |
| response = self.openai.chat.completions.create(model=openai_model, messages=messages, tools=tools) | |
| if response.choices[0].finish_reason=="tool_calls": | |
| message = response.choices[0].message | |
| tool_calls = message.tool_calls | |
| results = self.handle_tool_call(tool_calls) | |
| messages.append(message) | |
| messages.extend(results) | |
| else: | |
| done = True | |
| return response.choices[0].message.content | |
| if __name__ == "__main__": | |
| me = Me() | |
| with gr.Blocks(title="Meet Green Plate Castle Craves") as demo: | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| gr.Markdown("## **Meet Green Plate Castle Craves**") | |
| gr.Markdown("<p style='font-size: 1.2em; color: gray;'>Ask me any question about our services </p>") | |
| with gr.Column(scale=2): | |
| gr.Image("logo-elisda.jpg", height=150, show_label=False, container=False) | |
| gr.ChatInterface(me.chat, type="messages") | |
| demo.launch() | |