aimanathar commited on
Commit
1a43a9c
·
verified ·
1 Parent(s): 01e3034

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -29
app.py CHANGED
@@ -1,40 +1,125 @@
1
- from flask import Flask, request, jsonify
2
  from huggingface_hub import InferenceClient
3
- import os
4
 
5
- app = Flask(__name__)
 
 
6
 
7
- # Hugging Face Token (set in Space secrets as HF_TOKEN)
8
- HF_TOKEN = os.getenv("HF_TOKEN")
9
- client = InferenceClient(model="openai/gpt-oss-20b", token=HF_TOKEN)
10
 
11
- @app.route("/chat", methods=["POST"])
12
- def chat():
13
- try:
14
- data = request.get_json()
15
- user_message = data.get("message", "")
 
 
 
 
 
 
 
 
 
 
16
 
17
- messages = [
18
- {"role": "system", "content": "You are a friendly chatbot."},
19
- {"role": "user", "content": user_message}
20
- ]
21
 
22
- response = ""
23
- for msg in client.chat_completion(
24
- messages,
25
- max_tokens=256,
26
- stream=True,
27
- temperature=0.7,
28
- top_p=0.95
29
- ):
30
- if msg.choices and msg.choices[0].delta.content:
31
- response += msg.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- return jsonify({"reply": response})
 
34
 
35
- except Exception as e:
36
- return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
 
 
 
 
 
 
38
 
39
  if __name__ == "__main__":
40
- app.run(host="0.0.0.0", port=7860)
 
1
+ import gradio as gr
2
  from huggingface_hub import InferenceClient
 
3
 
4
+ # Hardcoded Token & Model
5
+ HF_TOKEN = "hf_your_token_here" # apna HF token paste karein
6
+ MODEL_NAME = "openai/gpt-oss-20b"
7
 
8
+ # 🔒 Hardcoded Practical Lists
9
+ hardcoded_answers = {
10
+ "chemistry class 9 practicals": """🔬 Chemistry Class IX (Practical Index)
11
 
12
+ - To separate the given mixture by physical method
13
+ - To determine the melting point of naphthalene
14
+ - To determine the boiling point of acetone
15
+ - To separate naphthalene from mixture of naphthalene and sand (sublimation)
16
+ - To separate alcohol and water by distillation
17
+ - To demonstrate that chemical reaction releases energy in the form of heat
18
+ - To prepare 100 mL of 0.1M sodium hydroxide solution
19
+ - To prepare 250 mL of 0.1M hydrochloric acid solution
20
+ - To prepare 100 mL of 0.1M sodium carbonate solution
21
+ - To prepare 100 mL of 0.1M NaOH by dilution of given solution
22
+ - To prepare pure copper sulphate crystals from impure sample
23
+ - To demonstrate miscible and immiscible liquids
24
+ - To demonstrate effect of temperature on solubility
25
+ - To demonstrate electrical conductivity of different solutions
26
+ - To demonstrate formation of a binary compound""",
27
 
28
+ "chemistry class 10 practicals": """🔬 Chemistry Class X (Practical Index)
 
 
 
29
 
30
+ - Identify sodium, calcium, strontium, barium, copper and potassium ions by flame test
31
+ - Standardize the given HCl solution volumetrically
32
+ - Determine exact molarity of Na₂CO₃ solution volumetrically
33
+ - Demonstrate that some natural substances are weak acids
34
+ - Classify substances as acidic, basic, or neutral
35
+ - Demonstrate decomposition of sugar into elements/compounds""",
36
+
37
+ "physics class 9 practicals": """⚙ Physics Class IX (Practical Index)
38
+
39
+ - To measure area of cross-section of a cylinder using vernier callipers
40
+ - To measure volume of a solid cylinder using vernier callipers
41
+ - To study motion of a ball rolling down an inclined plane (s vs t² graph)
42
+ - To determine acceleration due to gravity (g) by free fall method
43
+ - To find limiting friction by roller method
44
+ - To find resultant of two forces acting at a point by graphical method
45
+ - To verify principle of moments using a beam balance
46
+ - To study variation of time period of a pendulum with length and calculate g
47
+ - To determine density of a solid heavier than water using Archimedes principle
48
+ - To study temperature vs time graph (ice → water → steam)""",
49
+
50
+ "physics class 10 practicals": """⚙ Physics Class X (Practical Index)
51
+
52
+ - To verify the law of reflection of light
53
+ - To find refractive index of water using a concave mirror
54
+ - To determine critical angle of glass using semicircular slab/prism
55
+ - To trace path of a ray of light through a glass prism and measure deviation
56
+ - To find focal length of convex lens (parallel ray/parallax method)
57
+ - To set up an astronomical telescope
58
+ - To set up a microscope
59
+ - To verify Ohm’s law using wire as a conductor
60
+ - To study resistors in series circuit
61
+ - To study resistors in parallel circuit
62
+ - To determine resistance of a galvanometer by half-deflection method
63
+ - To trace magnetic field using a bar magnet"""
64
+ }
65
+
66
+
67
+ def respond(message, history: list[dict[str, str]]):
68
+ # ✅ Pehle check karein hardcoded answers
69
+ lower_msg = message.lower()
70
+ for key, answer in hardcoded_answers.items():
71
+ if key in lower_msg:
72
+ yield answer
73
+ return # yahan se return ho jayega, model call nahi hoga
74
 
75
+ # Agar hardcoded nahi mila toh model se response lo
76
+ client = InferenceClient(token=HF_TOKEN, model=MODEL_NAME)
77
 
78
+ messages = [{"role": "system", "content": "You are a friendly chatbot."}]
79
+ messages.extend(history)
80
+ messages.append({"role": "user", "content": message})
81
+
82
+ response = ""
83
+ for msg in client.chat_completion(
84
+ messages,
85
+ max_tokens=512,
86
+ stream=True,
87
+ temperature=0.7,
88
+ top_p=0.95
89
+ ):
90
+ if msg.choices and msg.choices[0].delta.content:
91
+ response += msg.choices[0].delta.content
92
+ yield response
93
+
94
+
95
+ # 💜 CSS aur UI wahi rakha jo aapke code me hai
96
+ custom_css = """ ... (same CSS as before) ... """
97
+
98
+ with gr.Blocks(css=custom_css) as demo:
99
+ with gr.Column():
100
+ gr.HTML("<div class='top-bar'>💬 Virtual Chatbot</div>")
101
+ chatbot = gr.Chatbot(elem_classes="chatbot", bubble_full_width=False, show_copy_button=False)
102
+ with gr.Row(elem_classes="input-area"):
103
+ msg = gr.Textbox(placeholder="Type your message...", lines=1)
104
+ send_btn = gr.Button("➤")
105
+
106
+ def user_submit(user_message, chat_history):
107
+ return "", chat_history + [(user_message, None)]
108
+
109
+ def bot_response(chat_history):
110
+ user_message = chat_history[-1][0]
111
+ response = ""
112
+ for partial in respond(user_message, [{"role": "user", "content": h[0]} for h in chat_history[:-1]]):
113
+ response = partial
114
+ chat_history[-1] = (chat_history[-1][0], response)
115
+ return chat_history
116
 
117
+ msg.submit(user_submit, [msg, chatbot], [msg, chatbot]).then(
118
+ bot_response, chatbot, chatbot
119
+ )
120
+ send_btn.click(user_submit, [msg, chatbot], [msg, chatbot]).then(
121
+ bot_response, chatbot, chatbot
122
+ )
123
 
124
  if __name__ == "__main__":
125
+ demo.launch(share=True)