Vishal1122 commited on
Commit
ba0b0b3
Β·
verified Β·
1 Parent(s): 7268110

New Logic Added

Browse files
Files changed (1) hide show
  1. app.py +105 -65
app.py CHANGED
@@ -1,79 +1,119 @@
1
  import gradio as gr
2
- import requests
3
- import json
 
 
 
 
 
 
 
4
 
5
  # Constants
6
- QUESTIONS_API = "https://agents-course-unit4-scoring.hf.space/questions"
7
- SUBMIT_API = "https://agents-course-unit4-scoring.hf.space/submit"
8
-
9
- # 1. Fetch evaluation questions from GAIA API
10
- def fetch_questions():
11
- response = requests.get(QUESTIONS_API)
12
- if response.status_code == 200:
13
- return response.json()
14
- else:
15
- return []
16
-
17
- # 2. Replace this function with your actual agent logic
18
  def process_question(question):
19
- # Dummy answer logic β€” change this with your own model/inference logic
20
- return "42" if "life" in question.lower() else "This is a placeholder answer"
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # 3. Submit answers to GAIA API
23
- def submit_answers(username, agent_code, answers):
24
- payload = {
 
 
25
  "username": username,
26
- "agent_code": agent_code,
27
- "answers": answers
28
  }
29
- headers = {"Content-Type": "application/json"}
30
- response = requests.post(SUBMIT_API, data=json.dumps(payload), headers=headers)
31
- if response.status_code == 200:
32
- return response.json()
33
- else:
34
- return {"error": f"Submission failed: {response.text}"}
35
-
36
- # 4. Main evaluation function
37
- def run_evaluation(username, agent_code):
38
- questions = fetch_questions()
39
- if not questions:
40
- return "❌ Failed to fetch questions. Please try again."
41
-
42
- answers = []
43
- for question in questions:
44
- task_id = question.get("task_id")
45
- question_text = question.get("question")
46
- answer = process_question(question_text)
47
- answers.append({
48
- "task_id": task_id,
49
- "submitted_answer": answer
50
- })
51
-
52
- result = submit_answers(username, agent_code, answers)
53
-
54
- if "error" in result:
55
- return result["error"]
56
-
57
- score = result.get("score", "N/A")
58
- feedback = result.get("feedback", "No feedback provided.")
59
- return f"βœ… Score: {score}/100\n\nπŸ“ Feedback:\n{feedback}"
60
-
61
- # 5. Gradio UI
 
 
 
 
 
 
 
 
 
 
62
  with gr.Blocks() as demo:
63
- gr.Markdown("# πŸ€– Unit 4 Agent Evaluation")
64
- gr.Markdown("Submit your Hugging Face username and agent Space URL below to get your score.")
 
65
 
66
- with gr.Row():
67
- username_input = gr.Text(label="Hugging Face Username", placeholder="e.g. your-username")
68
- agent_code_input = gr.Text(label="Agent Code URL", placeholder="https://huggingface.co/spaces/your-username/your-agent")
 
 
 
 
 
 
69
 
70
- evaluate_button = gr.Button("πŸš€ Run Evaluation")
71
- output_text = gr.Textbox(label="Result", lines=10)
 
 
 
 
 
72
 
73
- evaluate_button.click(
74
- fn=run_evaluation,
75
- inputs=[username_input, agent_code_input],
76
- outputs=output_text
77
  )
78
 
79
  demo.launch()
 
1
  import gradio as gr
2
+ from datasets import load_dataset, Dataset
3
+ from datetime import datetime, date
4
+ import os
5
+ from PIL import Image, ImageDraw, ImageFont
6
+ from huggingface_hub import login
7
+ from transformers import pipeline
8
+
9
+ # Authenticate with Hugging Face
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
+ # Load text-generation pipeline (FLAN-T5)
18
+ qa_pipeline = pipeline("text2text-generation", model="google/flan-t5-base")
19
+
20
+ # Process question using model
 
 
 
 
21
  def process_question(question):
22
+ if not question or not isinstance(question, str):
23
+ return "I don't understand the question."
24
+ result = qa_pipeline(question, max_new_tokens=50)
25
+ return result[0]["generated_text"].strip()
26
+
27
+ # Function to check user score
28
+ def check_user_score(username):
29
+ score_data = load_dataset(SCORES_DATASET, split="train", download_mode="force_redownload")
30
+ matches = [row for row in score_data if row["username"] == username]
31
+ return matches[0] if matches else None
32
+
33
+ # Check if user already has certificate
34
+ def has_certificate_entry(username):
35
+ cert_data = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
36
+ return any(row["username"] == username for row in cert_data)
37
 
38
+ # Add certificate entry
39
+ def add_certificate_entry(username, name, score):
40
+ ds = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
41
+ filtered_rows = [row for row in ds if row["username"] != username]
42
+ new_entry = {
43
  "username": username,
44
+ "score": score,
45
+ "timestamp": datetime.now().isoformat()
46
  }
47
+ filtered_rows.append(new_entry)
48
+ updated_ds = Dataset.from_list(filtered_rows)
49
+ updated_ds.push_to_hub(CERTIFICATES_DATASET)
50
+
51
+ # Generate certificate
52
+ def generate_certificate(name, score):
53
+ certificate_path = os.path.join(os.path.dirname(__file__), "templates", "certificate.png")
54
+ im = Image.open(certificate_path)
55
+ d = ImageDraw.Draw(im)
56
+
57
+ name_font = ImageFont.truetype("Quattrocento-Regular.ttf", 100)
58
+ date_font = ImageFont.truetype("Quattrocento-Regular.ttf", 48)
59
+
60
+ name = name.title()
61
+ d.text((1000, 740), name, fill="black", anchor="mm", font=name_font)
62
+ d.text((1480, 1170), str(date.today()), fill="black", anchor="mm", font=date_font)
63
+
64
+ pdf = im.convert("RGB")
65
+ pdf.save("certificate.pdf")
66
+
67
+ return im, "certificate.pdf"
68
+
69
+ # Handle certificate logic
70
+ def handle_certificate(name, profile: gr.OAuthProfile):
71
+ if profile is None:
72
+ return "You must be logged in with your Hugging Face account.", None, None
73
+
74
+ username = profile.username
75
+ user_score = check_user_score(username)
76
+
77
+ if not user_score:
78
+ return "You need to complete Unit 4 first.", None, None
79
+
80
+ score = user_score["score"]
81
+
82
+ if score < THRESHOLD_SCORE:
83
+ return f"Your score is {score}. You need at least {THRESHOLD_SCORE} to pass.", None, None
84
+
85
+ certificate_image, certificate_pdf = generate_certificate(name, score)
86
+ add_certificate_entry(username, name, score)
87
+ return "πŸŽ‰ Congratulations! Here's your certificate:", certificate_image, certificate_pdf
88
+
89
+ # Gradio UI
90
  with gr.Blocks() as demo:
91
+ gr.Markdown("# πŸŽ“ Agents Course - Get Your Final Certificate")
92
+ gr.Markdown("Welcome! Follow the steps below to receive your official certificate:")
93
+ gr.Markdown("⚠️ **Note**: Due to high demand, you might experience occasional bugs. If something doesn't work, please try again after a moment!")
94
 
95
+ with gr.Group():
96
+ gr.Markdown("## βœ… How it works")
97
+ gr.Markdown("""
98
+ 1. **Sign in** with your Hugging Face account using the button below.
99
+ 2. **Enter your full name** (this will appear on the certificate).
100
+ 3. Click **'Get My Certificate'** to check your score and download your certificate.
101
+ """)
102
+ gr.Markdown("---")
103
+ 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.")
104
 
105
+ gr.LoginButton()
106
+ with gr.Row():
107
+ name_input = gr.Text(label="Enter your name (this will appear on the certificate)")
108
+ generate_btn = gr.Button("Get my certificate")
109
+ output_text = gr.Textbox(label="Result")
110
+ cert_image = gr.Image(label="Your Certificate")
111
+ cert_file = gr.File(label="Download Certificate (PDF)", file_types=[".pdf"])
112
 
113
+ generate_btn.click(
114
+ fn=handle_certificate,
115
+ inputs=[name_input],
116
+ outputs=[output_text, cert_image, cert_file]
117
  )
118
 
119
  demo.launch()