Files changed (1) hide show
  1. app.py +54 -121
app.py CHANGED
@@ -1,121 +1,54 @@
1
- import gradio as gr
2
- from datasets import load_dataset, Dataset
3
- from datetime import datetime
4
- from datetime import date
5
- import io
6
- import os
7
- from PIL import Image, ImageDraw, ImageFont
8
- from huggingface_hub import login
9
-
10
- login(token=os.environ["HUGGINGFACE_TOKEN"])
11
-
12
- # Constants
13
- SCORES_DATASET = "agents-course/unit4-students-scores"
14
- CERTIFICATES_DATASET = "agents-course/course-certificates-of-excellence"
15
- THRESHOLD_SCORE = 30
16
-
17
- # Function to check user score
18
- def check_user_score(username):
19
- score_data = load_dataset(SCORES_DATASET, split="train", download_mode="force_redownload")
20
- matches = [row for row in score_data if row["username"] == username]
21
- return matches[0] if matches else None
22
-
23
- # Function to check if certificate entry exists
24
- def has_certificate_entry(username):
25
- cert_data = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
26
- print(username)
27
- return any(row["username"] == username for row in cert_data)
28
-
29
- # Function to add certificate entry
30
- def add_certificate_entry(username, name, score):
31
- # Load current dataset
32
- ds = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
33
-
34
- # Remove any existing entry with the same username
35
- filtered_rows = [row for row in ds if row["username"] != username]
36
-
37
- # Append the updated/new entry
38
- new_entry = {
39
- "username": username,
40
- "score": score,
41
- "timestamp": datetime.now().isoformat()
42
- }
43
- filtered_rows.append(new_entry)
44
-
45
- # Rebuild dataset and push
46
- updated_ds = Dataset.from_list(filtered_rows)
47
- updated_ds.push_to_hub(CERTIFICATES_DATASET)
48
-
49
- # Function to generate certificate PDF
50
- def generate_certificate(name, score):
51
- """Generate certificate image and PDF."""
52
- certificate_path = os.path.join(
53
- os.path.dirname(__file__), "templates", "certificate.png"
54
- )
55
- im = Image.open(certificate_path)
56
- d = ImageDraw.Draw(im)
57
-
58
- name_font = ImageFont.truetype("Quattrocento-Regular.ttf", 100)
59
- date_font = ImageFont.truetype("Quattrocento-Regular.ttf", 48)
60
-
61
- name = name.title()
62
- d.text((1000, 740), name, fill="black", anchor="mm", font=name_font)
63
-
64
- d.text((1480, 1170), str(date.today()), fill="black", anchor="mm", font=date_font)
65
-
66
- pdf = im.convert("RGB")
67
- pdf.save("certificate.pdf")
68
-
69
- return im, "certificate.pdf"
70
-
71
- # Main function to handle certificate generation
72
- def handle_certificate(name, profile: gr.OAuthProfile):
73
- if profile is None:
74
- return "You must be logged in with your Hugging Face account.", None
75
-
76
- username = profile.username
77
- user_score = check_user_score(username)
78
-
79
- if not user_score:
80
- return "You need to complete Unit 4 first.", None, None
81
-
82
- score = user_score["score"]
83
-
84
- if score < THRESHOLD_SCORE:
85
- return f"Your score is {score}. You need at least {THRESHOLD_SCORE} to pass.", None, None
86
-
87
- certificate_image, certificate_pdf = generate_certificate(name, score)
88
- add_certificate_entry(username, name, score)
89
- return "Congratulations! Here's your certificate:", certificate_image, certificate_pdf
90
-
91
- # Gradio interface
92
- with gr.Blocks() as demo:
93
- gr.Markdown("# ๐ŸŽ“ Agents Course - Get Your Final Certificate")
94
- gr.Markdown("Welcome! Follow the steps below to receive your official certificate:")
95
- gr.Markdown("โš ๏ธ **Note**: Due to high demand, you might experience occasional bugs. If something doesn't work, please try again after a moment!")
96
-
97
- with gr.Group():
98
- gr.Markdown("## โœ… How it works")
99
- gr.Markdown("""
100
- 1. **Sign in** with your Hugging Face account using the button below.
101
- 2. **Enter your full name** (this will appear on the certificate).
102
- 3. Click **'Get My Certificate'** to check your score and download your certificate.
103
- """)
104
- gr.Markdown("---")
105
- gr.Markdown("๐Ÿ“ **Note**: You must have completed [Unit 4](https://huggingface.co/learn/agents-course/unit4/introduction) and your Agent must have scored **above 30** to get your certificate.")
106
-
107
- gr.LoginButton()
108
- with gr.Row():
109
- name_input = gr.Text(label="Enter your name (this will appear on the certificate)")
110
- generate_btn = gr.Button("Get my certificate")
111
- output_text = gr.Textbox(label="Result")
112
- cert_image = gr.Image(label="Your Certificate")
113
- cert_file = gr.File(label="Download Certificate (PDF)", file_types=[".pdf"])
114
-
115
- generate_btn.click(
116
- fn=handle_certificate,
117
- inputs=[name_input],
118
- outputs=[output_text, cert_image, cert_file]
119
- )
120
-
121
- demo.launch()
 
1
+ import streamlit as st
2
+ from langchain_groq import ChatGroq
3
+ from langchain_community.utilities import ArxivAPIWrapper, WikipediaAPIWrapper
4
+ from langchain_community.tools import ArxivQueryRun, WikipediaQueryRun, DuckDuckGoSearchRun
5
+ from langchain.agents import initialize_agent, AgentType
6
+ from langchain.callbacks import StreamlitCallbackHandler
7
+ import os
8
+ from dotenv import load_dotenv
9
+
10
+ # Used the inbuilt tools of Arxiv and Wikipedia
11
+ api_wrapper_arxiv = ArxivAPIWrapper(top_k_results=1, doc_content_chars_max=250)
12
+ arxiv = ArxivQueryRun(api_wrapper=api_wrapper_arxiv)
13
+
14
+ api_wrapper_wiki = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=250)
15
+ wiki = WikipediaQueryRun(api_wrapper=api_wrapper_wiki)
16
+
17
+ search = DuckDuckGoSearchRun(name="Search")
18
+
19
+ st.title("Langchain - Chat with Search")
20
+ """
21
+ In this example, we're using `StreamlitCallbackHandler` to display the thoughts and actions of an agent in an interactive Streamlit app.
22
+ Try more LangChain ๐Ÿค Streamlit Agent examples at [github.com/langchain-ai/streamlit-agent](https://github.com/langchain-ai/streamlit-agent).
23
+ """
24
+
25
+ # Sidebar for settings
26
+ st.sidebar.title("Settings")
27
+ api_key = st.sidebar.text_input("Enter your Groq API Key:", type="password")
28
+
29
+ if "messages" not in st.session_state:
30
+ st.session_state["messages"] = [
31
+ {"role":"assistant", "content":"Hi, I am a Chatbot who can search the web. How can I help you ?"}
32
+ ]
33
+
34
+ for msg in st.session_state.messages:
35
+ st.chat_message(msg["role"]).write(msg["content"])
36
+
37
+ if prompt:=st.chat_input(placeholder="What is machine learning ?"):
38
+ st.session_state.messages.append({"role":"user", "content":prompt})
39
+ st.chat_message("user").write(prompt)
40
+
41
+ llm = ChatGroq(groq_api_key=api_key, model_name="Llama3-8b-8192", streaming=True)
42
+ tools = [search, arxiv, wiki]
43
+
44
+ search_agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True)
45
+
46
+ with st.chat_message("assistant"):
47
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
48
+ response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
49
+ st.session_state.messages.append({'role':'assistant', "content":response})
50
+ st.write(response)
51
+
52
+
53
+
54
+