Scan Food Labels Instantly on Your Android Device

Scanning food labels has evolved from manual reading to instant analysis. Modern apps can now identify ingredients, detect allergens, and even flag additives based on your specific dietary needs. This guide walks you through building a free, high-performance scanner for Android that combines optical character recognition with a lightweight language model. The result is a responsive app that provides instant, personalized ingredient analysis without requiring a subscription or premium tier.
The core idea is simple: capture an image, extract text, and send it to an AI for interpretation. By leveraging a free, keyless API, you avoid the complexity of managing tokens or API keys. The model used here is designed to refuse less than commercial assistants while maintaining strict safety boundaries, making it ideal for diverse dietary queries. It is important to note that while the domain contains the brand Groq, the site is not affiliated with Groq.
This project uses Kotlin and Jetpack Compose for the interface, ML Kit for OCR, and a standard HTTP client to interact with the AI endpoint. The architecture follows MVVM principles, ensuring a clean separation between the camera feed, the OCR engine, and the AI analysis logic. You will learn how to handle camera permissions, process images efficiently, and format prompts that yield accurate allergen detection. This approach is significantly faster than waiting for cloud-based multimodal models to process the same image.
Frequently asked questions
What is OCR in food scanning?
Optical Character Recognition (OCR) converts images of text into machine-readable data. In this app, ML Kit extracts ingredient lists from package photos, allowing the AI to process the raw text rather than analyzing the image directly. This reduces latency and cost.
How does the free API differ from paid LLMs?
The free API uses a 35B parameter open-weight model fine-tuned for lower refusal rates. It lacks multimodal capabilities like image processing or audio, but it handles text analysis efficiently. Unlike commercial models, it requires no account or API key, simplifying deployment for hobby projects.
Which is better: React Native or Kotlin for this app?
Kotlin with Jetpack Compose offers native performance and direct access to camera APIs. React Native is faster to prototype but may introduce overhead for real-time camera feeds. For a dedicated food scanner, native code ensures smoother OCR integration and better battery efficiency.
How accurate is the ingredient analysis?
Accuracy depends on OCR quality and model context limits. The model supports a 32,000 token context window, allowing it to read full ingredient lists. However, it is text-only, so poor lighting or curved labels may reduce OCR accuracy. Always verify critical allergens manually.
What are the rate limits for this API?
The API allows one request per second with bursts of three. It supports two parallel connections per IP. Daily limits are 10,000 requests or 10 million tokens. If you exceed these, you receive a 429 status code with a Retry-After header. Plan your scanning sessions accordingly.
How do I handle allergen detection?
Pass the extracted text to the AI with a prompt specifying allergens. The model is fine-tuned to refuse less, so it will likely identify common allergens like gluten or nuts. You can customize the prompt to include your specific dietary restrictions for more personalized results.
What is the difference between streaming and non-streaming responses?
Streaming returns tokens as they are generated, providing a real-time typing effect. Non-streaming waits for the entire response before returning it. For food scanning, non-streaming is often sufficient since the text is short, but streaming offers a smoother user experience for longer analyses.
Which is better for local vs cloud processing?
Cloud processing offloads computation to the server, saving battery and device storage. Local processing requires a powerful device and larger models. For this app, the cloud API is preferred due to its speed and the ability to use a 35B parameter model without local hardware constraints.
Step by step
- Setup Project — Create a new Android project with Kotlin and Jetpack Compose. Add dependencies for ML Kit and OkHttp. Configure camera permissions in the manifest.
- Implement OCR — Use CameraX to capture images and ML Kit to extract text. Store the extracted text in a ViewModel for further processing.
- Connect API — Send the extracted text to the free AI API using the /v1/chat/completions endpoint. Parse the response and display the analysis in the UI.
- Optimize and Test — Implement caching, error handling, and performance optimizations. Test with various food labels and gather user feedback for improvements.
Setting Up the Android Project
Begin by creating a new Android project in Android Studio using Kotlin and Jetpack Compose. Ensure you target the latest API level and enable camera permissions in your manifest. You will need to add dependencies for ML Kit for OCR and a networking library like OkHttp or the standard Java HTTP client. The MVVM architecture is recommended to keep the UI logic separate from the data processing logic.
Configure the camera feed using CameraX, which provides a consistent API across different Android devices. Set up a preview view that displays the live camera feed and allows the user to tap a button to capture an image. Once captured, the image is passed to the ML Kit OCR engine, which returns the raw text. This text is then stored in a ViewModel state, ready to be sent to the AI API.
The UI should display the captured image, the extracted text, and the AI analysis. Use Compose to create a responsive layout that adapts to different screen sizes. Implement a loading state while the API request is in progress, and handle errors gracefully by displaying a message to the user. The goal is to provide a seamless experience that feels instant and reliable.
Camera and OCR Integration
Use CameraX to capture high-resolution images. Pass the image to ML Kit's On-Device OCR API. This ensures fast processing without network latency. The extracted text is then cleaned and prepared for the API request.
MVVM Architecture Setup
Create a ViewModel to manage the state of the app. It should hold the extracted text, the AI response, and loading states. Use LiveData or StateFlow to observe these states in the Compose UI, ensuring that the interface updates automatically as data changes.
- Add camera permissions to AndroidManifest.xml
- Include ML Kit and OkHttp dependencies in build.gradle
- Set up CameraX preview and capture use cases
- Configure ViewModel with StateFlow for UI updates
// Example ViewModel setup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class FoodScannerViewModel : ViewModel() {
private val _extractedText = MutableStateFlow<String?>(null)
val extractedText: StateFlow<String?> = _extractedText
fun setExtractedText(text: String) {
_extractedText.value = text
}
}Connecting to the Free AI API
The API endpoint is https://api.groqkeyfreeapi.com/v1. It is OpenAI-compatible, meaning you can use standard libraries like the OpenAI SDK or simple HTTP requests. The model name is "free-ai". No API key is required, which simplifies the setup process. You can use the /v1/chat/completions endpoint to send the extracted text and receive an analysis.
Construct a JSON payload with the message content. The system prompt should instruct the AI to analyze the ingredients for allergens and dietary suitability. For example, you can ask it to list any allergens present and highlight any unusual additives. The model is fine-tuned to refuse less, so it will provide detailed responses even for complex ingredient lists.
Handle the API response by parsing the JSON and extracting the assistant's message. Display this text in the UI. Implement error handling for common issues like network timeouts or rate limits. The API returns a 429 status code if you exceed the rate limit, so you should implement a retry mechanism with exponential backoff. This ensures that the app remains responsive even under heavy load.
API Request Structure
Send a POST request to /v1/chat/completions. Include the model name "free-ai" and the messages array. The system message defines the role, and the user message contains the extracted text. This structure is compatible with most OpenAI SDKs.
Error Handling and Retries
Catch HTTP 429 errors and implement a retry logic with a delay. The API allows bursts of three requests per second, so you can send multiple requests quickly if needed. For 503 errors, wait 2-5 seconds before retrying. This ensures robustness against temporary server busy states.
- Use the /v1/chat/completions endpoint
- Set the model to "free-ai"
- Include a system prompt for allergen detection
- Implement retry logic for 429 and 503 errors
import requests
url = "https://api.groqkeyfreeapi.com/v1/chat/completions"
headers = {"Content-Type": "application/json", "User-Agent": "FoodScanner/1.0"}
data = {
"model": "free-ai",
"messages": [
{"role": "system", "content": "You are a helpful assistant that analyzes food labels."},
{"role": "user", "content": "Analyze these ingredients: sugar, wheat flour, nuts."}
]
}
response = requests.post(url, headers=headers, json=data)
print(response.json()['choices'][0]['message']['content'])
Prompt Engineering for Dietary Needs
Prompt engineering is crucial for getting accurate results. Start with a system prompt that defines the AI's role as a dietary analyst. Then, in the user message, include the extracted text and any specific dietary constraints. For example, you can ask the AI to check for gluten, dairy, or soy. The model's lower refusal rate means it will provide detailed answers even for niche dietary needs.
You can also include a few-shot examples in the prompt to guide the AI's response format. For instance, you can provide an example of how the AI should list allergens and highlight additives. This helps ensure consistency in the output. The API supports a context window of 32,000 tokens, so you can include a large amount of text without hitting limits.
Test different prompts to see which ones yield the best results. You might find that a more concise prompt works better for quick scans, while a detailed prompt is better for comprehensive analysis. The goal is to balance accuracy with speed, ensuring that the user gets the information they need without unnecessary delay.
System Prompt Design
Define the AI's role clearly. Use phrases like 'You are a dietary expert' to set the tone. This helps the AI focus on relevant information and ignore irrelevant details in the ingredient list.
Few-Shot Examples
Provide examples of input text and desired output. This guides the AI to follow a specific format, such as listing allergens first, then additives. Consistent formatting makes it easier to parse the response programmatically.
- Define a clear role in the system prompt
- Include specific dietary constraints in the user message
- Use few-shot examples for consistent formatting
- Test different prompt variations for accuracy
messages = [
{"role": "system", "content": "You are a dietary expert."},
{"role": "user", "content": "Ingredients: sugar, wheat, nuts. Check for gluten."}
]
# Send to API
response = requests.post(url, headers=headers, json={"model": "free-ai", "messages": messages})Optimizing for Performance
Performance is key for a smooth user experience. Use ML Kit's on-device OCR to minimize latency. The OCR process should be fast enough to provide near-instant results. Once the text is extracted, send it to the API immediately. The API's low latency is due to its optimized inference engine, which processes requests quickly.
Consider caching frequent queries to reduce API usage. If a user scans the same product multiple times, you can store the result locally and display it instantly. This also reduces the load on the API and ensures that the app works offline for previously scanned items. Use a local database like Room to store scanned products and their analyses.
Optimize the UI to handle loading states gracefully. Show a skeleton screen or a spinner while the API request is in progress. This prevents the UI from freezing and provides visual feedback to the user. Ensure that the camera feed remains smooth while the OCR and API processing are happening in the background.
Caching Strategies
Use Room database to store scanned products. Cache the API response for each product. This reduces API calls and provides instant results for repeat scans. Implement a cache invalidation strategy to ensure data freshness.
Background Processing
Use Kotlin Coroutines to handle OCR and API requests in the background. This keeps the UI thread free for responsive interactions. Ensure that long-running tasks do not block the main thread, which could cause the app to appear unresponsive.
- Use ML Kit for fast on-device OCR
- Cache API responses in a local database
- Use Kotlin Coroutines for background tasks
- Implement skeleton screens for loading states
// Example of caching with Room
@Entity
class ScannedProduct(val id: String, val ingredients: String, val analysis: String)
// Use Room to store and retrieve cached results
val db = Room.databaseBuilder(context, AppDatabase::class.java, "food-scanner-db").build()
val dao = db.foodDao()
dao.insertProduct(ScannedProduct("123", "sugar, wheat", "Contains gluten"))
Handling Edge Cases
Real-world food labels can be tricky. Curved surfaces, poor lighting, and small fonts can affect OCR accuracy. Implement a preview mode that allows the user to adjust the camera angle and focus before capturing. Provide visual cues to guide the user in positioning the label correctly. This reduces the need for multiple scans and improves the overall user experience.
Handle cases where the OCR fails to extract any text. Display a message asking the user to try again or adjust the lighting. You can also provide an option to manually enter the ingredients if the OCR fails. This ensures that the app remains useful even in suboptimal conditions. The AI can still analyze manually entered text with the same accuracy.
Consider the diversity of food labels. Different countries have different labeling standards and languages. If you plan to support multiple languages, ensure that the OCR and AI models support them. The free API is primarily English-focused, so multilingual support may require additional configuration or a different model.
OCR Error Recovery
If OCR returns empty or garbled text, prompt the user to retake the photo. Provide hints on lighting and angle. Allow manual text entry as a fallback option. This ensures that the app remains functional even when OCR fails.
Label Variability
Account for curved labels and varying font sizes. Use CameraX's autofocus and exposure controls to improve image quality. Consider using image preprocessing techniques like contrast enhancement to improve OCR accuracy.
- Provide camera angle guidance
- Allow manual text entry as a fallback
- Support multiple languages if needed
- Use image preprocessing to improve OCR
// Manual text entry fallback
fun onManualEntry(text: String) {
viewModel.setExtractedText(text)
viewModel.analyzeIngredients(text)
}Testing and Validation
Test the app with a variety of food labels to ensure accuracy. Use labels with different ingredient lists, allergens, and additives. Compare the AI's analysis with known information to validate its accuracy. You can also ask users to provide feedback on the app's performance and accuracy. This helps identify any patterns of errors or inconsistencies.
Monitor the API usage to ensure that you stay within the rate limits. Implement logging to track the number of requests, latency, and error rates. This data can help you optimize the app's performance and identify any bottlenecks. The API's stateless nature means that each request is independent, so you can scale easily by adding more instances if needed.
Conduct user testing to gather feedback on the user experience. Ask users about the speed, accuracy, and ease of use of the app. Use this feedback to make improvements to the UI, OCR, and AI prompts. Continuous testing and iteration are key to building a successful app.
Accuracy Validation
Compare AI outputs with known ingredient lists. Use a dataset of labeled food products to test the app's accuracy. Track false positives and false negatives to identify areas for improvement in the prompt or OCR.
User Feedback Loop
Implement a feedback button in the app. Allow users to report incorrect analyses. Use this data to refine the prompts and improve the OCR accuracy. Regular updates based on user feedback ensure that the app remains accurate and useful.
- Test with diverse food labels
- Monitor API usage and latency
- Conduct user testing for UX feedback
- Implement a feedback loop for continuous improvement
# Example logging of API usage
import logging
logging.basicConfig(filename='api_usage.log', level=logging.INFO)
logging.info(f'Request sent to {url} with status {response.status_code}')
Deployment and Distribution
Once the app is tested and validated, prepare it for deployment. Generate a signed APK or Android App Bundle (AAB) for distribution. Ensure that all permissions are correctly configured and that the app meets the guidelines of the target app store. Submit the app to the Google Play Store or distribute it directly via APK.
Consider the app's size and performance. Optimize the APK by removing unused resources and code. Use ProGuard or R8 to shrink and obfuscate the code. This reduces the app's size and improves startup time. Ensure that the app is compatible with a wide range of Android devices and OS versions.
Monitor the app's performance after deployment. Use analytics to track user engagement, crash rates, and API usage. This data can help you identify any issues that need to be addressed. Regular updates with bug fixes and new features will keep users engaged and satisfied.
App Store Submission
Prepare the AAB file and fill out the app store listing details. Include screenshots, descriptions, and privacy policy. Ensure that the app meets all store guidelines. Submit for review and address any feedback from the store reviewers.
Post-Launch Monitoring
Use analytics tools to monitor app performance. Track crash reports and user feedback. Use this data to prioritize bug fixes and feature updates. Regular updates ensure that the app remains stable and relevant.
- Generate signed APK or AAB
- Optimize APK size with ProGuard
- Submit to Google Play Store
- Monitor post-launch performance
# Generate signed APK
./gradlew assembleRelease
# Upload to Play Store
./gradlew publishReleaseFuture Enhancements
Consider adding features like barcode scanning to automatically identify products. This would allow users to scan a barcode and instantly retrieve the AI analysis without needing to capture the label. Integrate with a product database to enhance the analysis with additional information like nutritional facts and reviews.
Explore using multimodal models to analyze the image directly. This could improve accuracy by allowing the AI to see the label's layout and context. However, this would require a different API or model that supports image input. The current text-only approach is efficient and cost-effective for most use cases.
Add support for voice input, allowing users to dictate their dietary needs. This would make the app more accessible to users with visual impairments or those who prefer voice commands. Integrate with a speech-to-text API to convert voice input into text for the AI analysis.
Barcode Integration
Add barcode scanning to automatically fetch product data. Integrate with a product database to enhance the AI analysis. This reduces the need for OCR and provides more accurate results.
Multimodal Support
Explore using multimodal models that can analyze images directly. This could improve accuracy by providing context from the label's layout. However, it may increase latency and cost compared to the text-only approach.
- Integrate barcode scanning
- Explore multimodal models
- Add voice input support
- Enhance with product database
// Example barcode scanning setup
val barcodeScanner = BarcodeScanning.getClient(BarcodeScanningOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_UPC_A, Barcode.FORMAT_EAN_13)
.build())
barcodeScanner.process(imageProxy)
.addOnSuccessListener { barcodes ->
// Process barcode
}
Test the keyless API directly in your browser or via the Python SDK to see Groq's speed in action without configuring any keys.