Spaces:
Sleeping

File size: 11,495 Bytes
1d5d03b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
033e0b4
cd36ef9
 
 
033e0b4
1d5d03b
 
 
033e0b4
cd36ef9
 
033e0b4
1d5d03b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
033e0b4
cd36ef9
 
033e0b4
1d5d03b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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_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)}"
            




# Example 
utext = "ਮੈਂ ਪੰਜਾਬੀ ਵਿੱਚ ਗੱਲ ਕਰਦਾ ਹਾਂ۔"
print("Detected language:", detect_language_name(utext))



# 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 = "Elisda"
        # reader = PdfReader("shaji/linkedin.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 Elisda") as demo:
        with gr.Row():
            with gr.Column(scale=3):
                gr.Markdown("## **Meet Elisda**")
                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()