adarsh commited on
Commit
1a02dac
·
1 Parent(s): 70bf20e

init setup

Browse files
Files changed (3) hide show
  1. app.py +79 -0
  2. gemini_integ.py +70 -0
  3. requirements.txt +147 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from pinecone import Pinecone
5
+ from langchain.embeddings import HuggingFaceEmbeddings
6
+ from langchain.prompts import PromptTemplate
7
+ from gemini_integ import GeminiIntegration
8
+
9
+ # Load environment variables
10
+
11
+ load_dotenv()
12
+
13
+ PINECONE_API_KEY = os.getenv('PINECONE_API_KEY')
14
+ index_name = "apple-chatbot"
15
+
16
+ # Initialize Pinecone
17
+ pc = Pinecone(api_key=PINECONE_API_KEY)
18
+ index = pc.Index(index_name)
19
+
20
+ # Load embeddings
21
+ def load_embeddings():
22
+ return HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
23
+
24
+ embeddings = load_embeddings()
25
+
26
+ def get_similarity_search(query_embedding, top_k):
27
+ search_results = index.query(
28
+ namespace="ns1", # Replace with actual namespace
29
+ vector=query_embedding,
30
+ top_k=top_k,
31
+ include_values=True,
32
+ include_metadata=True
33
+ )
34
+ return search_results
35
+
36
+ # Prompt Template
37
+ prompt_template = PromptTemplate(
38
+ input_variables=["context", "question"],
39
+ template="""
40
+ Helpful Answer for Farmer:
41
+ Use the following pieces of information to answer the farmer's question about apple orchard management:
42
+
43
+ Context: {context}
44
+ Question: {question}
45
+
46
+ If you don't know the answer, say "I'm not sure, but I can try to find more information for you."
47
+ Only return the helpful answer below and nothing else.
48
+ Helpful Answer:
49
+ """
50
+ )
51
+
52
+ def get_rag_response(query, top_k=2):
53
+ query_embed = embeddings.embed_query(query)
54
+ search_res = get_similarity_search(query_embed, top_k=top_k)
55
+ llm = GeminiIntegration()
56
+ prompt = prompt_template.format(context=search_res, question=query)
57
+ response = llm.generate_response(query=prompt)
58
+ return response
59
+
60
+ # Gradio Interface
61
+ def chatbot_interface(query):
62
+ response = get_rag_response(query, top_k=3)
63
+ return response
64
+
65
+ # Gradio UI
66
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
67
+ gr.Markdown("""<h1 style='text-align: center; color: #4CAF50;'>🍏 Smart Orchard AI Chatbot 🍏</h1>""")
68
+ gr.Markdown("""<p style='text-align: center;'>Ask anything about apple cultivation, soil types, pest management, and more!</p>""")
69
+
70
+ with gr.Row():
71
+ query_input = gr.Textbox(label="Enter Your Query", placeholder="Ask about apple orchard management...")
72
+ submit_btn = gr.Button("🔍 Search")
73
+
74
+ response_output = gr.Textbox(label="Response", interactive=False)
75
+ submit_btn.click(chatbot_interface, inputs=query_input, outputs=response_output)
76
+
77
+ gr.Markdown("""<p style='text-align: center;'>Powered by <b>Gemini API</b> and <b>Pinecone Vector Database</b></p>""")
78
+
79
+ demo.launch()
gemini_integ.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from dotenv import load_dotenv
4
+
5
+ load_dotenv()
6
+
7
+ import os
8
+ import google.generativeai as genai
9
+ from dotenv import load_dotenv
10
+ import logging
11
+
12
+ # Configure logging
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ class GeminiIntegration:
17
+ """Handles interaction with Google's Gemini API"""
18
+
19
+ def __init__(self, model_name: str = "gemini-2.0-flash", embedding_model: str = "text-embedding-004"):
20
+ self.model_name = model_name
21
+ self.embedding_model = embedding_model
22
+ self._configure_gemini()
23
+
24
+ def _configure_gemini(self):
25
+ """Configure Gemini API client"""
26
+ try:
27
+ api_key = os.getenv("GEMINI_API_KEY")
28
+ if not api_key:
29
+ raise ValueError("GEMINI_API_KEY not found in environment variables")
30
+ genai.configure(api_key=api_key)
31
+ logger.info("Gemini API configured successfully.")
32
+ except Exception as e:
33
+ logger.error(f"Failed to configure Gemini: {str(e)}")
34
+ raise
35
+
36
+ def generate_response(self, query: str, context: str = "") -> str:
37
+ """Generate a response from Gemini given a query and optional context"""
38
+ try:
39
+ prompt = f"Context: {context}\n\nQuestion: {query}"
40
+ # prompt checking
41
+ print("Prompt checking: ")
42
+ print(prompt)
43
+
44
+
45
+ response = genai.GenerativeModel(self.model_name).generate_content(prompt)
46
+ return response.text
47
+ except Exception as e:
48
+ logger.error(f"Response generation failed: {str(e)}")
49
+ raise
50
+
51
+ def embed_text(self, text: str):
52
+ """Generate text embeddings using Gemini"""
53
+ try:
54
+ response = genai.embed_content(
55
+ model=self.embedding_model,
56
+ content=text,
57
+ task_type="retrieval_query"
58
+ )
59
+ return response['embedding']
60
+ except Exception as e:
61
+ logger.error(f"Embedding generation failed: {str(e)}")
62
+ raise
63
+
64
+ # example usage
65
+ gem = GeminiIntegration()
66
+ # response = gem.generate_response(query="Tell me about apple cultivation?")
67
+ # print(response)
68
+
69
+ print("Gemini Integeration working! ")
70
+
requirements.txt ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ aiohappyeyeballs==2.4.6
3
+ aiohttp==3.10.11
4
+ aiosignal==1.3.2
5
+ annotated-types==0.7.0
6
+ anyio==4.8.0
7
+ async-timeout==4.0.3
8
+ attrs==25.1.0
9
+ blinker==1.9.0
10
+ cachetools==5.5.2
11
+ certifi==2025.1.31
12
+ cffi==1.17.1
13
+ charset-normalizer==3.4.1
14
+ click==8.1.8
15
+ colorama==0.4.6
16
+ contourpy==1.3.1
17
+ cryptography==44.0.1
18
+ cycler==0.12.1
19
+ dataclasses-json==0.6.7
20
+ exceptiongroup==1.2.2
21
+ fastapi==0.115.8
22
+ ffmpy==0.5.0
23
+ filelock==3.17.0
24
+ Flask==3.1.0
25
+ fonttools==4.56.0
26
+ frozenlist==1.5.0
27
+ fsspec==2025.2.0
28
+ google-ai-generativelanguage==0.6.15
29
+ google-api-core==2.24.1
30
+ google-api-python-client==2.161.0
31
+ google-auth==2.38.0
32
+ google-auth-httplib2==0.2.0
33
+ google-generativeai==0.8.4
34
+ googleapis-common-protos==1.68.0
35
+ gradio==5.17.1
36
+ gradio_client==1.7.1
37
+ greenlet==3.1.1
38
+ grpcio==1.70.0
39
+ grpcio-status==1.70.0
40
+ h11==0.14.0
41
+ httpcore==1.0.7
42
+ httplib2==0.22.0
43
+ httpx==0.28.1
44
+ httpx-sse==0.4.0
45
+ huggingface-hub==0.29.1
46
+ idna==3.10
47
+ iniconfig==2.0.0
48
+ itsdangerous==2.2.0
49
+ Jinja2==3.1.5
50
+ joblib==1.4.2
51
+ jsonpatch==1.33
52
+ jsonpointer==3.0.0
53
+ jwt==1.3.1
54
+ kiwisolver==1.4.8
55
+ langchain==0.3.19
56
+ langchain-community==0.3.18
57
+ langchain-core==0.3.37
58
+ langchain-huggingface==0.1.2
59
+ langchain-pinecone==0.2.3
60
+ langchain-tests==0.3.12
61
+ langchain-text-splitters==0.3.6
62
+ langsmith==0.3.9
63
+ markdown-it-py==3.0.0
64
+ MarkupSafe==2.1.5
65
+ marshmallow==3.26.1
66
+ matplotlib==3.10.0
67
+ mdurl==0.1.2
68
+ mpmath==1.3.0
69
+ multidict==6.1.0
70
+ mypy-extensions==1.0.0
71
+ networkx==3.4.2
72
+ numpy==1.26.4
73
+ opencv-python==4.11.0.86
74
+ orjson==3.10.15
75
+ packaging==24.2
76
+ pandas==2.2.3
77
+ pillow==11.1.0
78
+ pinecone==5.4.2
79
+ pinecone-client==6.0.0
80
+ pinecone-plugin-inference==3.1.0
81
+ pinecone-plugin-interface==0.0.7
82
+ pluggy==1.5.0
83
+ propcache==0.3.0
84
+ proto-plus==1.26.0
85
+ protobuf==5.29.3
86
+ psutil==7.0.0
87
+ py-cpuinfo==9.0.0
88
+ pyasn1==0.6.1
89
+ pyasn1_modules==0.4.1
90
+ pycparser==2.22
91
+ pydantic==2.10.6
92
+ pydantic-settings==2.8.0
93
+ pydantic_core==2.27.2
94
+ pydub==0.25.1
95
+ Pygments==2.19.1
96
+ pyparsing==3.2.1
97
+ pytesseract==0.3.13
98
+ pytest==8.3.4
99
+ pytest-asyncio==0.25.3
100
+ pytest-socket==0.7.0
101
+ python-dateutil==2.9.0.post0
102
+ python-dotenv==1.0.1
103
+ python-multipart==0.0.20
104
+ pytz==2025.1
105
+ PyYAML==6.0.2
106
+ regex==2024.11.6
107
+ requests==2.32.3
108
+ requests-toolbelt==1.0.0
109
+ rich==13.9.4
110
+ rsa==4.9
111
+ ruff==0.9.7
112
+ safehttpx==0.1.6
113
+ safetensors==0.5.2
114
+ scikit-learn==1.6.1
115
+ scipy==1.15.2
116
+ seaborn==0.13.2
117
+ semantic-version==2.10.0
118
+ sentence-transformers==3.4.1
119
+ shellingham==1.5.4
120
+ six==1.17.0
121
+ sniffio==1.3.1
122
+ SQLAlchemy==2.0.38
123
+ starlette==0.45.3
124
+ sympy==1.13.1
125
+ syrupy==4.8.2
126
+ tenacity==9.0.0
127
+ threadpoolctl==3.5.0
128
+ tokenizers==0.21.0
129
+ tomli==2.2.1
130
+ tomlkit==0.13.2
131
+ torch==2.6.0
132
+ torchvision==0.21.0
133
+ tqdm==4.67.1
134
+ transformers==4.49.0
135
+ typer==0.15.1
136
+ typing-inspect==0.9.0
137
+ typing_extensions==4.12.2
138
+ tzdata==2025.1
139
+ ultralytics==8.3.78
140
+ ultralytics-thop==2.0.14
141
+ uritemplate==4.1.1
142
+ urllib3==2.3.0
143
+ uvicorn==0.34.0
144
+ websockets==14.2
145
+ Werkzeug==3.1.3
146
+ yarl==1.18.3
147
+ zstandard==0.23.0