mikaelJ46 commited on
Commit
259a295
Β·
verified Β·
1 Parent(s): e40a5cc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -72
app.py CHANGED
@@ -2,80 +2,80 @@
2
  # UNEB Primary 7/6 Exam Preparation Platform
3
  # Multi-AI System: Gemini (Primary) β†’ Cohere β†’ HF (Fallback)
4
  # ========================================================
5
-
6
  import os
7
  import json
8
- with gr.Tabs():
9
- with gr.Tab("✏️ Draw Answers"):
10
- canvas = gr.Sketchpad(
11
- label="Draw or write your answers here",
12
- type="pil",
13
- height=500,
14
- brush=gr.Brush(
15
- colors=["#000000", "#0000FF", "#FF0000"],
16
- default_size=4
17
- )
18
- )
19
- canvas_status = gr.Textbox(
20
- label="Canvas Status",
21
- interactive=False,
22
- value="Ready to draw"
23
- )
24
-
25
- with gr.Tab("πŸ“Έ Upload Photo"):
26
- upload_image = gr.Image(
27
- label="Upload photo of your written work",
28
- type="pil",
29
- height=500
30
- )
31
- upload_status = gr.Textbox(
32
- label="Upload Status",
33
- interactive=False,
34
- value="Ready to upload"
35
- )
36
-
37
- with gr.Tab(" Type Answers"):
38
- gr.Markdown("""
39
- ### πŸ“ Type Your Answers
40
- **Instructions:** Type each answer in the box below. Use one of these formats:
41
- - **Option A (Recommended):** Type answers separated by blank lines
42
- ```
43
- Answer to question 1 goes here
44
-
45
- Answer to question 2 goes here
46
-
47
- Answer to question 3 goes here
48
- ```
49
- - **Option B:** Type with labels
50
- ```
51
- Answer 1: Your answer here
52
- Answer 2: Your answer here
53
- Answer 3: Your answer here
54
- ```
55
- - **Option C:** Type with Q labels
56
- ```
57
- Q1: Your answer here
58
- Q2: Your answer here
59
- Q3: Your answer here
60
- ```
61
- """)
62
-
63
- typed_answers = gr.Textbox(
64
- label="Type Your Answers Here",
65
- lines=20,
66
- placeholder="Type your answers using any of the formats shown above...",
67
- elem_classes="answer-input"
68
- )
 
 
69
 
70
- # Combined submit button (outside tabs, still inside right column)
71
- with gr.Row():
72
- submit_btn = gr.Button(" Submit for Correction", variant="primary", size="lg")
73
 
74
- submit_status = gr.Textbox(
75
- label="Submission Status",
76
- interactive=False,
77
- lines=2
78
- )
79
  model="command-r-plus-08-2024",
80
  message=prompt,
81
  temperature=temperature
@@ -85,7 +85,7 @@ import json
85
  print(f"βœ— Cohere attempt {attempt+1} failed: {e}")
86
  if attempt < max_retries - 1:
87
  time.sleep(1)
88
-
89
  # Try Hugging Face (Fallback) - text only
90
  if hf_client:
91
  try:
@@ -98,7 +98,7 @@ import json
98
  return completion.choices[0].message.content, "hf"
99
  except Exception as e:
100
  print(f"βœ— HF failed: {e}")
101
-
102
  return " All AI services failed. Please try again later.", "error"
103
 
104
  # ---------- 3. Uganda Primary Curriculum Syllabus (P6 & P7 Only, by Subject) ----------
 
2
  # UNEB Primary 7/6 Exam Preparation Platform
3
  # Multi-AI System: Gemini (Primary) β†’ Cohere β†’ HF (Fallback)
4
  # ========================================================
 
5
  import os
6
  import json
7
+ from datetime import datetime
8
+ import gradio as gr
9
+ import time
10
+ from io import BytesIO
11
+ from PIL import Image
12
+ import csv
13
+ from pathlib import Path
14
+ import re
15
+
16
+ # ---------- 1. Configure AI Systems ----------
17
+ try:
18
+ import google.generativeai as genai
19
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
20
+ gemini_model = genai.GenerativeModel('gemini-2.0-flash-exp')
21
+ print("βœ“ Gemini AI initialized (PRIMARY with Vision)")
22
+ except Exception as e:
23
+ print(f"βœ— Gemini Error: {e}")
24
+ gemini_model = None
25
+
26
+ try:
27
+ import cohere
28
+ cohere_client = cohere.Client(os.getenv("COHERE_API_KEY"))
29
+ print("βœ“ Cohere initialized (SECONDARY)")
30
+ except Exception as e:
31
+ print(f"βœ— Cohere Error: {e}")
32
+ cohere_client = None
33
+
34
+ try:
35
+ from huggingface_hub import InferenceClient
36
+ hf_client = InferenceClient(api_key=os.environ.get("HF_TOKEN"))
37
+ print("βœ“ Hugging Face initialized (FALLBACK)")
38
+ except Exception as e:
39
+ print(f"βœ— HF Error: {e}")
40
+ hf_client = None
41
+
42
+
43
+ def ask_ai(prompt, temperature=0.7, max_retries=2, image=None):
44
+ """Try models: Gemini β†’ Cohere β†’ HF
45
+ If image provided, only Gemini can process it"""
46
+
47
+ # Try Gemini first (Primary) - handles both text and images
48
+ if gemini_model:
49
+ for attempt in range(max_retries):
50
+ try:
51
+ if image:
52
+ response = gemini_model.generate_content(
53
+ [prompt, image],
54
+ generation_config=genai.types.GenerationConfig(
55
+ temperature=temperature,
56
+ )
57
+ )
58
+ else:
59
+ response = gemini_model.generate_content(
60
+ prompt,
61
+ generation_config=genai.types.GenerationConfig(
62
+ temperature=temperature,
63
+ )
64
+ )
65
+ return response.text, "gemini"
66
+ except Exception as e:
67
+ print(f"βœ— Gemini attempt {attempt+1} failed: {e}")
68
+ if attempt < max_retries - 1:
69
+ time.sleep(1)
70
 
71
+ if image:
72
+ return " Image analysis requires Gemini AI. Please check API configuration.", "error"
 
73
 
74
+ # Try Cohere (Secondary) - text only
75
+ if cohere_client:
76
+ for attempt in range(max_retries):
77
+ try:
78
+ response = cohere_client.chat(
79
  model="command-r-plus-08-2024",
80
  message=prompt,
81
  temperature=temperature
 
85
  print(f"βœ— Cohere attempt {attempt+1} failed: {e}")
86
  if attempt < max_retries - 1:
87
  time.sleep(1)
88
+
89
  # Try Hugging Face (Fallback) - text only
90
  if hf_client:
91
  try:
 
98
  return completion.choices[0].message.content, "hf"
99
  except Exception as e:
100
  print(f"βœ— HF failed: {e}")
101
+
102
  return " All AI services failed. Please try again later.", "error"
103
 
104
  # ---------- 3. Uganda Primary Curriculum Syllabus (P6 & P7 Only, by Subject) ----------