File size: 4,045 Bytes
abcb1a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8de7846
abcb1a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
import gradio as gr
import pandas as pd
import json
import inspect

# --- Basic Agent Definition ---
class BasicAgent:
    def __init__(self):
        print("BasicAgent initialized.")

    def __call__(self, question: str) -> str:
        print(f"Agent received question (first 50 chars): {question[:50]}...")
        fixed_answer = "This is a default answer."
        print(f"Agent returning fixed answer: {fixed_answer}")
        return fixed_answer


# --- Main Function: run_and_save ---
def run_and_save(profile: gr.OAuthProfile | None, task_id: int):
    """
    Loads questions.json, finds the question by task_id,
    runs the agent, and appends the answer to result_log.json.
    """
    # --- Authentication Check ---
    if not profile:
        print("User not logged in.")
        return "Please Login to Hugging Face with the button.", None

    username = profile.username
    print(f"βœ… User logged in: {username}")

    # --- Instantiate Agent ---
    try:
        agent = BasicAgent()
    except Exception as e:
        return f"Error initializing agent: {e}", None

    # --- Load Questions ---
    questions_path = "questions.json"
    if not os.path.exists(questions_path):
        return f"❌ {questions_path} not found.", None

    try:
        with open(questions_path, "r", encoding="utf-8") as f:
            questions_data = json.load(f)
    except json.JSONDecodeError as e:
        return f"Error decoding {questions_path}: {e}", None

    if not isinstance(questions_data, list):
        return "Invalid format: questions.json must contain a list.", None

    # --- Find Question by Task ID ---
    question_item = next((q for q in questions_data if q.get("task_id") == task_id), None)
    if not question_item:
        return f"No question found for task_id {task_id}.", None

    question_text = question_item.get("question", "")
    print(f"🟦 Running agent for task_id {task_id}...")

    # --- Run Agent ---
    try:
        submitted_answer = agent(question_text)
        result = {
            "Task ID": task_id,
            "Question": question_text,
            "Submitted Answer": submitted_answer
        }
    except Exception as e:
        result = {
            "Task ID": task_id,
            "Question": question_text,
            "Submitted Answer": f"AGENT ERROR: {e}"
        }

    # --- Save to result_log.json ---
    result_log_path = "result_log.json"
    if os.path.exists(result_log_path):
        try:
            with open(result_log_path, "r", encoding="utf-8") as f:
                result_log = json.load(f)
                if not isinstance(result_log, list):
                    result_log = []
        except Exception:
            result_log = []
    else:
        result_log = []

    result_log.append(result)

    with open(result_log_path, "w", encoding="utf-8") as f:
        json.dump(result_log, f, indent=4, ensure_ascii=False)

    print(f"βœ… Result saved to {result_log_path}")

    results_df = pd.DataFrame([result])
    return f"βœ… Answer saved locally for task_id {task_id}", results_df


# --- Gradio Interface ---
with gr.Blocks() as demo:
    gr.Markdown("# JUST ANOTHER AGENT")
    gr.Markdown(
        """
        **Instructions:**
        1. Login to Hugging Face using the button below.  
        2. Enter the Task ID from your `questions.json`.  
        3. Click **Run Agent & Save Answer**.  
        4. The result will be appended to `result_log.json` for manual upload.
        """
    )

    profile = gr.LoginButton()
    task_id_input = gr.Number(label="Enter Task ID", precision=0)
    run_button = gr.Button("Run Agent & Save Answer")

    status_output = gr.Textbox(label="Status", lines=3, interactive=False)
    results_table = gr.DataFrame(label="Result Log (Latest Entry)")

    run_button.click(
        fn=run_and_save,
        inputs=[profile, task_id_input],
        outputs=[status_output, results_table]
    )

if __name__ == "__main__":
    print("Launching Gradio interface...")
    demo.launch(debug=True, share=False)