File size: 5,228 Bytes
37185e0
 
cf36601
37185e0
052a8fc
37185e0
cdbe688
 
37185e0
 
cdbe688
 
 
 
 
 
 
 
 
 
 
052a8fc
cdbe688
 
 
 
052a8fc
cdbe688
37185e0
87ccea1
 
3be9484
37185e0
c0d54a6
37185e0
 
3be9484
87ccea1
 
 
 
 
 
c0d54a6
3be9484
37185e0
3be9484
 
 
 
 
 
 
37185e0
 
 
 
 
3be9484
 
37185e0
c0d54a6
 
37185e0
 
052a8fc
 
 
 
 
 
 
 
 
 
2bd7b24
cdbe688
052a8fc
 
 
 
cdbe688
 
 
 
 
2bd7b24
 
87ccea1
2bd7b24
12d8a5c
052a8fc
2bd7b24
12d8a5c
87ccea1
2bd7b24
 
 
 
 
052a8fc
2bd7b24
 
 
 
12d8a5c
 
 
 
2bd7b24
 
 
 
 
 
cdbe688
2bd7b24
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
from serpapi import GoogleSearch  # Corrected SerpAPI import
import os
from datetime import datetime  # Import datetime for date validation

# Load API keys securely from environment variables
serpapi_key = os.getenv("SERPAPI_API_KEY")  # Add your SerpAPI key to your environment variables
groq_api_key = os.getenv("GROQ_CLOUD_API_KEY")

# Function to use SerpAPI to get the LinkedIn URL
def get_linkedin_profile_via_serpapi(name, city):
    query = f"{name} LinkedIn {city}"
    params = {
        "q": query,
        "hl": "en",
        "gl": "us",
        "api_key": serpapi_key,
    }
    search = GoogleSearch(params)
    results = search.get_dict()
    
    # Look for LinkedIn profile in search results
    for result in results.get("organic_results", []):
        if "linkedin.com" in result.get("link", ""):
            return result["link"]
    
    return "LinkedIn profile not found"

# Helper function to call Groq Cloud LLM API to generate and correct the email
def generate_and_correct_email(bio, company_name, role):
    url = "https://api.groq.com/openai/v1/chat/completions"  # Updated API URL for Groq Cloud
    headers = {
        "Authorization": f"Bearer {groq_api_key}",  # Use the API key securely from environment
        "Content-Type": "application/json",
    }
    
    # Updated prompt to ask the model to generate AND correct the email
    prompt = f"""
    Write a professional email applying for a {role} position at {company_name}. Use this bio: {bio}.
    The email should include an introduction, relevant experience, skills, and a closing.
    Ensure that the email is grammatically correct and formal.
    """
    
    # Construct the data payload for the API request
    data = {
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ],
        "model": "llama3-8b-8192"  # Use the appropriate model from Groq Cloud
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        # Extract the generated email content from the API response
        return response.json()["choices"][0]["message"]["content"].strip()
    else:
        # Print or log the error for debugging
        print(f"Error: {response.status_code}, {response.text}")
        return "Error generating email. Please check your API key or try again later."

# Function to validate the DOB format (DD-MM-YYYY)
def validate_dob(dob):
    try:
        # Attempt to parse the DOB to the expected format
        datetime.strptime(dob, "%d-%m-%Y")
        return True
    except ValueError:
        # Return False if the format is invalid
        return False

# Main function to create the email and allow for saving, editing, or copying
def create_email(name, dob, city, company_name, role, email, phone):
    # Validate the DOB format (DD-MM-YYYY)
    if not validate_dob(dob):
        return "Invalid Date of Birth format. Please use DD-MM-YYYY."

    # Step 1: Fetch LinkedIn profile using SerpAPI
    linkedin_profile = get_linkedin_profile_via_serpapi(name, city)
    
    # Use a placeholder bio (you can extend this to fetch real bio data from LinkedIn)
    bio = f"{name} is a professional in {city}."
    
    # Step 2: Generate the email using Groq Cloud LLM
    generated_email = generate_and_correct_email(bio, company_name, role)
    
    # Step 3: Add the user's email, phone number, and LinkedIn profile to the signature
    signature = f"\n\nBest regards,\n{name}\nEmail: {email}\nPhone: {phone}\nLinkedIn: {linkedin_profile}"

    # Return the final polished email with the signature
    return generated_email + signature

# Define interface with Gradio
def gradio_ui():
    # Define inputs
    name_input = gr.Textbox(label="Name", placeholder="Enter your name")
    dob_input = gr.Textbox(label="Date of Birth", placeholder="Enter your date of birth (DD-MM-YYYY)")
    city_input = gr.Textbox(label="City", placeholder="Enter your city of residence")
    
    company_name_input = gr.Textbox(label="Company Name", placeholder="Enter the name of the company you are applying to")
    role_input = gr.Textbox(label="Role", placeholder="Enter the role you are applying for")
    
    email_input = gr.Textbox(label="Email Address", placeholder="Enter your email address")
    phone_input = gr.Textbox(label="Phone Number", placeholder="Enter your phone number")
    
    # Define output for the generated email
    email_output = gr.Textbox(label="Generated Email", placeholder="Your generated email will appear here", lines=10)
    
    # Create the Gradio interface
    demo = gr.Interface(
        fn=create_email,  # Function to call when the user submits
        inputs=[name_input, dob_input, city_input, company_name_input, role_input, email_input, phone_input],
        outputs=[email_output],
        title="Email Writing AI Agent",
        description="Generate a professional email for a job application by providing your basic info.",
        allow_flagging="never"  # Disable flagging
    )
    
    # Launch the Gradio app
    demo.launch()

# Start the Gradio app when running the script
if __name__ == "__main__":
    gradio_ui()